Adding space/padding to a UILabel
up vote
108
down vote
favorite
I have a UILabel where I want to add space in the top and in the bottom.
With minimun height in constrainst I've modified it to:

EDIT:
To do this I've used:
override func drawTextInRect(rect: CGRect) {
var insets: UIEdgeInsets = UIEdgeInsets(top: 0.0, left: 10.0, bottom: 0.0, right: 10.0)
super.drawTextInRect(UIEdgeInsetsInsetRect(rect, insets))
}
But I've to find a different method because if I write more than two lines the problem is the same:

ios uilabel padding
add a comment |
up vote
108
down vote
favorite
I have a UILabel where I want to add space in the top and in the bottom.
With minimun height in constrainst I've modified it to:

EDIT:
To do this I've used:
override func drawTextInRect(rect: CGRect) {
var insets: UIEdgeInsets = UIEdgeInsets(top: 0.0, left: 10.0, bottom: 0.0, right: 10.0)
super.drawTextInRect(UIEdgeInsetsInsetRect(rect, insets))
}
But I've to find a different method because if I write more than two lines the problem is the same:

ios uilabel padding
1
Possible duplicate of UILabel text margin
– gblazex
Mar 4 '16 at 10:16
add a comment |
up vote
108
down vote
favorite
up vote
108
down vote
favorite
I have a UILabel where I want to add space in the top and in the bottom.
With minimun height in constrainst I've modified it to:

EDIT:
To do this I've used:
override func drawTextInRect(rect: CGRect) {
var insets: UIEdgeInsets = UIEdgeInsets(top: 0.0, left: 10.0, bottom: 0.0, right: 10.0)
super.drawTextInRect(UIEdgeInsetsInsetRect(rect, insets))
}
But I've to find a different method because if I write more than two lines the problem is the same:

ios uilabel padding
I have a UILabel where I want to add space in the top and in the bottom.
With minimun height in constrainst I've modified it to:

EDIT:
To do this I've used:
override func drawTextInRect(rect: CGRect) {
var insets: UIEdgeInsets = UIEdgeInsets(top: 0.0, left: 10.0, bottom: 0.0, right: 10.0)
super.drawTextInRect(UIEdgeInsetsInsetRect(rect, insets))
}
But I've to find a different method because if I write more than two lines the problem is the same:

ios uilabel padding
ios uilabel padding
edited Feb 6 '17 at 12:51
Moritz
57.1k19131184
57.1k19131184
asked Dec 13 '14 at 14:14
Annachiara
547259
547259
1
Possible duplicate of UILabel text margin
– gblazex
Mar 4 '16 at 10:16
add a comment |
1
Possible duplicate of UILabel text margin
– gblazex
Mar 4 '16 at 10:16
1
1
Possible duplicate of UILabel text margin
– gblazex
Mar 4 '16 at 10:16
Possible duplicate of UILabel text margin
– gblazex
Mar 4 '16 at 10:16
add a comment |
27 Answers
27
active
oldest
votes
up vote
83
down vote
accepted
If you want to stick with UILabel, without subclassing it, Mundi has given you a clear solution.
If alternatively you would be willing to avoid wrapping the UILabel with a UIView, you could use UITextView to enable the use of UIEdgeInsets (padding) or subclass UILabel to support UIEdgeInsets.
Using a UITextView you would only need to provide the insets (OBJ-C):
textView.textContainerInset = UIEdgeInsetsMake(10, 0, 10, 0);
Alternative, if you subclass UILabel, an example to this approach would be overriding the drawTextInRect method
(OBJ-C)
- (void)drawTextInRect:(CGRect)uiLabelRect {
UIEdgeInsets myLabelInsets = {10, 0, 10, 0};
[super drawTextInRect:UIEdgeInsetsInsetRect(uiLabelRect, myLabelInsets)];
}
You could additionally provide your new subclassed UILabel with a insets variable for TOP, LEFT, BOTTOM and RIGHT.
An example code could be:
In .h (OBJ-C)
float topInset, leftInset,bottomInset, rightInset;
In .m (OBJ-C)
- (void)drawTextInRect:(CGRect)uiLabelRect {
[super drawTextInRect:UIEdgeInsetsInsetRect(uiLabelRect, UIEdgeInsetsMake(topInset,leftInset,bottomInset,rightInset))];
}
EDIT #1:
From what I have seen, it seems you have to override the intrinsicContentSize of the UILabel when subclassing it.
So you should override intrinsicContentSize like:
- (CGSize) intrinsicContentSize {
CGSize intrinsicSuperViewContentSize = [super intrinsicContentSize] ;
intrinsicSuperViewContentSize.height += topInset + bottomInset ;
intrinsicSuperViewContentSize.width += leftInset + rightInset ;
return intrinsicSuperViewContentSize ;
}
And add the following method to edit your insets, instead of editing them individually:
- (void) setContentEdgeInsets:(UIEdgeInsets)edgeInsets {
topInset = edgeInsets.top;
leftInset = edgeInsets.left;
rightInset = edgeInsets.right;
bottomInset = edgeInsets.bottom;
[self invalidateIntrinsicContentSize] ;
}
It will update the size of your UILabel to match the edge insets and cover multiline necessity you referred.
Edit #2
After searching a bit I have found this Gist with a IPInsetLabel. If none of those solutions work you could try it out.
Edit #3
There was similar question (duplicate) about this matter.
For a full list of available solutions, see this answer: UILabel text margin
Sorry but I've alreay used: ` override func drawTextInRect(rect: CGRect) { var insets: UIEdgeInsets = UIEdgeInsets(top: 0.0, left: 10.0, bottom: 0.0, right: 10.0) super.drawTextInRect(UIEdgeInsetsInsetRect(rect, insets)) } ` it doesn't work because the result is the same, don't work dynamically..
– Annachiara
Dec 13 '14 at 17:50
Did you tried with a UITextView instead of a UILabel? Or do you really need to use an UILabel?
– nunofmendes
Dec 13 '14 at 21:34
@Annachiara check the edit I've made. See if it works.
– nunofmendes
Dec 14 '14 at 11:54
Ok. Did it work the textview? Sorry for not writing in Swift but I am still in Obj-C mode. My goal with that code was to help you reach some conclusion. Hope it did.
– nunofmendes
Dec 14 '14 at 16:53
Using TextView and some storyboard settings and self.textview.textContainerInset = UIEdgeInsetsMake(0, 10, 10, 10); It finally works ! Thanks !
– Annachiara
Dec 14 '14 at 16:58
|
show 5 more comments
up vote
109
down vote
I have tried with it on Swift 4.2, hopefully it work for you!
@IBDesignable class PaddingLabel: UILabel {
@IBInspectable var topInset: CGFloat = 5.0
@IBInspectable var bottomInset: CGFloat = 5.0
@IBInspectable var leftInset: CGFloat = 7.0
@IBInspectable var rightInset: CGFloat = 7.0
override func drawText(in rect: CGRect) {
let insets = UIEdgeInsets.init(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawText(in: rect.inset(by: insets))
}
override var intrinsicContentSize: CGSize {
let size = super.intrinsicContentSize
return CGSize(width: size.width + leftInset + rightInset,
height: size.height + topInset + bottomInset)
}
}
Or you can use CocoaPods here https://github.com/levantAJ/PaddingLabel
pod 'PaddingLabel', '1.1'
1
This worked so well! Thanks, mate. Cheers.
– Felipe
May 3 at 6:53
this worked pretty good, thank you!
– Wilson
May 8 at 21:28
2
The uilabel width is not changing, causing the text become "..."
– neobie
May 12 at 6:09
1
@Tai Le , thanks for sharing, I have used it in tableview, I don't know why its triming the text , eg. student becomes studen,
– vishwa.deepak
Aug 30 at 6:04
1
Changing the return statement toreturn CGSize(width: max(size.width + leftInset + rightInset, 10000), height: size.height + topInset + bottomInset)solved the issue, just FYI!
– Tim
Nov 10 at 16:16
|
show 3 more comments
up vote
70
down vote
Swift 3
import UIKit
class PaddingLabel: UILabel {
@IBInspectable var topInset: CGFloat = 5.0
@IBInspectable var bottomInset: CGFloat = 5.0
@IBInspectable var leftInset: CGFloat = 5.0
@IBInspectable var rightInset: CGFloat = 5.0
override func drawText(in rect: CGRect) {
let insets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}
override var intrinsicContentSize: CGSize {
get {
var contentSize = super.intrinsicContentSize
contentSize.height += topInset + bottomInset
contentSize.width += leftInset + rightInset
return contentSize
}
}
}
just a little comment: set this class to label in identity inspector(custom class) and use new attribute in attribute inspector named label padding. also below 5 padding is effectless
– iman kazemayni
Jan 23 at 10:48
This doesn't always work correctly with multiline labels, because when the label calculates its height, it assumes zero padding.
– fhucho
Feb 22 at 16:37
add a comment |
up vote
61
down vote
You can do it properly from IB :
- change the text to attributed

- go to dropdown list with "..."

- you will see some padding properties for the lines, paragraphs and text change indent first line or anything you want

- check the result

1
In my storyboard I can see the text change but when I run the app. The text doesn´t show the change... T_T.. my label is inside of an custom cell, are there any problem?
– A. Trejo
Feb 17 '16 at 20:11
1
@A.Trejo May be your custom cell set the label property at run time.
– Pierre-Yves Guillemet
Feb 19 '16 at 9:05
In SB right margin can't has negative value. Do it in code.style.tailIndent = -30.0. Still can't do top and bottom indent.
– Nik Kov
Nov 25 '16 at 5:41
1
Changes can appear on storyboard but when you run the app there are no changes.
– Rhenz
May 30 '17 at 2:41
1
This is not applicable when you set text programatically.
– Nij
Jul 16 at 11:43
add a comment |
up vote
33
down vote
SWIFT 3/4
Easy to use solution, available for all UILabel child in project.
Example:
let label = UILabel()
label.<Do something>
label.padding = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 0)
UILabel Extension
import UIKit
extension UILabel {
private struct AssociatedKeys {
static var padding = UIEdgeInsets()
}
public var padding: UIEdgeInsets? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.padding) as? UIEdgeInsets
}
set {
if let newValue = newValue {
objc_setAssociatedObject(self, &AssociatedKeys.padding, newValue as UIEdgeInsets!, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
override open func draw(_ rect: CGRect) {
if let insets = padding {
self.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
} else {
self.drawText(in: rect)
}
}
override open var intrinsicContentSize: CGSize {
guard let text = self.text else { return super.intrinsicContentSize }
var contentSize = super.intrinsicContentSize
var textWidth: CGFloat = frame.size.width
var insetsHeight: CGFloat = 0.0
if let insets = padding {
textWidth -= insets.left + insets.right
insetsHeight += insets.top + insets.bottom
}
let newSize = text.boundingRect(with: CGSize(width: textWidth, height: CGFloat.greatestFiniteMagnitude),
options: NSStringDrawingOptions.usesLineFragmentOrigin,
attributes: [NSAttributedStringKey.font: self.font], context: nil)
contentSize.height = ceil(newSize.size.height) + insetsHeight
return contentSize
}
}
please briefly explain your answer, and do not only post code.
– lmiguelvargasf
May 24 '17 at 1:27
5
Nice solution. I think the code is self-explanatory.
– Jano
Jul 21 '17 at 8:16
4
Your extension cancel the 0 value to numberOfLines
– Antoine Bodart
Aug 4 '17 at 14:09
This is great, but Im having issues with multiple lines, even thought I add numbers of lines 2 or leave at 0, it always shows one. you know how to solve it?
– Mago Nicolas Palacios
Nov 8 '17 at 14:14
1
@AntoineBodart did you manage to solve the numberOfLines problem?
– Mago Nicolas Palacios
Nov 8 '17 at 14:14
|
show 7 more comments
up vote
32
down vote
Just use a UIView as a superview and define a fixed margin to the label with auto layout.
1
drawTextInRectworks only for 1 line,intrinsicContentSizedoes not work with horizontal padding. Wrap UILabel inside UIView is the good way to go
– onmyway133
Jun 3 '15 at 8:31
4
If you're in IB, now is the time to remember the menu Editor -> Embed In -> View. Just select your UILabel first :)
– Graham Perks
Apr 26 '17 at 18:58
add a comment |
up vote
16
down vote
Just use a UIButton, its already built in. Turn off all the extra button features and you have a label that you can set edge instets on.
let button = UIButton()
button.contentEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
button.setTitle("title", for: .normal)
button.tintColor = .white // this will be the textColor
button.isUserInteractionEnabled = false
1
Hey this is a great tip! No extensions required! :-D
– Felipe Ferri
Aug 16 '17 at 14:35
1
SettingisUserInteractionEnabled = falseis handy to disable it.
– mxcl
Sep 11 '17 at 5:56
Great tip... I'd rather do this than going for an extension.
– Ross
Jan 14 at 15:21
Nice tip, with the big advantage that it can also be done in the Interface Builder
– Ely
Sep 13 at 8:42
The best solution without subclassing and etc.
– MeGaPk
Nov 19 at 12:42
add a comment |
up vote
9
down vote
Without Storyboard:
class PaddingLabel: UILabel {
var topInset: CGFloat
var bottomInset: CGFloat
var leftInset: CGFloat
var rightInset: CGFloat
required init(withInsets top: CGFloat, _ bottom: CGFloat,_ left: CGFloat,_ right: CGFloat) {
self.topInset = top
self.bottomInset = bottom
self.leftInset = left
self.rightInset = right
super.init(frame: CGRect.zero)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func drawText(in rect: CGRect) {
let insets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}
override var intrinsicContentSize: CGSize {
get {
var contentSize = super.intrinsicContentSize
contentSize.height += topInset + bottomInset
contentSize.width += leftInset + rightInset
return contentSize
}
}
}
Usage:
let label = PaddingLabel(8, 8, 16, 16)
label.font = .boldSystemFont(ofSize: 16)
label.text = "Hello World"
label.backgroundColor = .black
label.textColor = .white
label.textAlignment = .center
label.layer.cornerRadius = 8
label.clipsToBounds = true
label.sizeToFit()
view.addSubview(label)
Result:

Works, but do you know how to make it accept multiple lines? Just change init with "PaddingLabel(withInsets: 8, 8, 16, 16)"
– Camilo Ortegón
Aug 11 '17 at 20:12
add a comment |
up vote
6
down vote
Swift 3 Code with Implementation Example
class UIMarginLabel: UILabel {
var topInset: CGFloat = 0
var rightInset: CGFloat = 0
var bottomInset: CGFloat = 0
var leftInset: CGFloat = 0
override func drawText(in rect: CGRect) {
let insets: UIEdgeInsets = UIEdgeInsets(top: self.topInset, left: self.leftInset, bottom: self.bottomInset, right: self.rightInset)
self.setNeedsLayout()
return super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}
}
class LabelVC: UIViewController {
//Outlets
@IBOutlet weak var labelWithMargin: UIMarginLabel!
override func viewDidLoad() {
super.viewDidLoad()
//Label settings.
labelWithMargin.leftInset = 10
view.layoutIfNeeded()
}
}
Don't forget to add class name UIMarginLabel in storyboard label object.
Happy Coding!
add a comment |
up vote
6
down vote
Swift 3, iOS10 solution:
open class UIInsetLabel: UILabel {
open var insets : UIEdgeInsets = UIEdgeInsets() {
didSet {
super.invalidateIntrinsicContentSize()
}
}
open override var intrinsicContentSize: CGSize {
var size = super.intrinsicContentSize
size.width += insets.left + insets.right
size.height += insets.top + insets.bottom
return size
}
override open func drawText(in rect: CGRect) {
return super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}
}
add a comment |
up vote
5
down vote
Subclass UILabel. (File-New-File- CocoaTouchClass-make Subclass of UILabel).
// sampleLabel.swift
import UIKit
class sampleLabel: UILabel {
let topInset = CGFloat(5.0), bottomInset = CGFloat(5.0), leftInset = CGFloat(8.0), rightInset = CGFloat(8.0)
override func drawTextInRect(rect: CGRect) {
let insets: UIEdgeInsets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawTextInRect(UIEdgeInsetsInsetRect(rect, insets))
}
override func intrinsicContentSize() -> CGSize {
var intrinsicSuperViewContentSize = super.intrinsicContentSize()
intrinsicSuperViewContentSize.height += topInset + bottomInset
intrinsicSuperViewContentSize.width += leftInset + rightInset
return intrinsicSuperViewContentSize
}
}
On ViewController:
override func viewDidLoad() {
super.viewDidLoad()
let labelName = sampleLabel(frame: CGRectMake(0, 100, 300, 25))
labelName.text = "Sample Label"
labelName.backgroundColor = UIColor.grayColor()
labelName.textColor = UIColor.redColor()
labelName.shadowColor = UIColor.blackColor()
labelName.font = UIFont(name: "HelveticaNeue", size: CGFloat(22))
self.view.addSubview(labelName)
}
OR Associate custom UILabel class on Storyboard as Label's class.
i would up vote if you change those hardcoded values into class properties, i am already using this code.
– Juan Boero
Apr 8 '16 at 21:43
@ Juan : drawTextInRect is a default class property of UILabel which we are unable to override using code. The best practice to subclass UILabel and add required frame change. Anyhow, it is convenient as Inheritance feature.
– A.G
Apr 11 '16 at 6:16
this is correct, however as of Swift 3 at least, intrinsicContentSize is not a function but rather a property, so should be "override var intrinsicContentSize: CGFloat {}" instead of "override func intrinsicContentSize", just a note.
– joey
Jun 9 '17 at 7:05
add a comment |
up vote
4
down vote
I edited a little in the accepted answer. There is a problem when leftInset and rightInset increase, a part of text will be disappeared, b/c the width of label will be narrowed but the height does not increase as figure:

To resolve this problem you need to re-calculate height of text as follow:
@IBDesignable class PaddingLabel: UILabel {
@IBInspectable var topInset: CGFloat = 20.0
@IBInspectable var bottomInset: CGFloat = 20.0
@IBInspectable var leftInset: CGFloat = 20.0
@IBInspectable var rightInset: CGFloat = 20.0
override func drawTextInRect(rect: CGRect) {
let insets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawTextInRect(UIEdgeInsetsInsetRect(rect, insets))
}
override func intrinsicContentSize() -> CGSize {
var intrinsicSuperViewContentSize = super.intrinsicContentSize()
let textWidth = frame.size.width - (self.leftInset + self.rightInset)
let newSize = self.text!.boundingRectWithSize(CGSizeMake(textWidth, CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: self.font], context: nil)
intrinsicSuperViewContentSize.height = ceil(newSize.size.height) + self.topInset + self.bottomInset
return intrinsicSuperViewContentSize
}
}
and result:

I hope to help some people in the same situation as me.
2
If you plan to use Swift 3.0, you must change function names, as new Apple language completely breaks previous func definition. So,override func drawTextInRect(rect: CGRect)becomesoverride func drawText(in rect: CGRect)andoverride func intrinsicContentSize() -> CGSizebecomesoverride var intrinsicContentSize : CGSizeEnjoy!
– DoK
Sep 30 '16 at 20:06
add a comment |
up vote
4
down vote
As per Swift 4.2 (Xcode 10 beta 6) "UIEdgeInsetsInsetRect" being deprecated.
I've also declared the class public to make it more useful.
public class UIPaddedLabel: UILabel {
@IBInspectable var topInset: CGFloat = 5.0
@IBInspectable var bottomInset: CGFloat = 5.0
@IBInspectable var leftInset: CGFloat = 7.0
@IBInspectable var rightInset: CGFloat = 7.0
public override func drawText(in rect: CGRect) {
let insets = UIEdgeInsets.init(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawText(in: rect.inset(by: insets))
}
public override var intrinsicContentSize: CGSize {
let size = super.intrinsicContentSize
return CGSize(width: size.width + leftInset + rightInset,
height: size.height + topInset + bottomInset)
}
public override func sizeToFit() {
super.sizeThatFits(intrinsicContentSize)
}
}
It works well. But I try to use it inside a CollectionViewCell and it doesn't resize well after reuse (event after sizeToFit and layoutIfNeeded). Any id how to resize it?
– Bogy
Sep 19 at 8:25
1
I did update sizeToFit() to make it work with reusable view
– Bogy
Sep 20 at 12:44
sizeToFit()should be public as: "Overriding instance method must be as accessible as its enclosing type"
– psyFi
Oct 23 at 18:57
add a comment |
up vote
3
down vote
In Swift 3
best and simple way
class UILabelPadded: UILabel {
override func drawText(in rect: CGRect) {
let insets = UIEdgeInsets.init(top: 0, left: 5, bottom: 0, right: 5)
super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}
}
add a comment |
up vote
2
down vote
Easy padding (Swift 3.0, Alvin George answer):
class NewLabel: UILabel {
override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
return self.bounds.insetBy(dx: CGFloat(15.0), dy: CGFloat(15.0))
}
override func draw(_ rect: CGRect) {
super.drawText(in: self.bounds.insetBy(dx: CGFloat(5.0), dy: CGFloat(5.0)))
}
}
add a comment |
up vote
2
down vote
Another option without subclassing would be to:
- Set label
text
sizeToFit()
then increase label height a little to simulate padding
label.text = "someText"
label.textAlignment = .center
label.sizeToFit()
label.frame = CGRect( x: label.frame.x, y: label.frame.y,width: label.frame.width + 20,height: label.frame.height + 8)
Surprisingly, this was all I needed, just modified a little to this:label.frame = CGRect( x: label.frame.origin.x - 10, y: label.frame.origin.y - 4, width: label.frame.width + 20,height: label.frame.height + 8)the -10 and -4 for centralizing
– Mofe-hendy Ejegi
Feb 10 at 6:01
add a comment |
up vote
1
down vote
Easy way
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.view.addSubview(makeLabel("my title",x: 0, y: 100, w: 320, h: 30))
}
func makeLabel(title:String, x:CGFloat, y:CGFloat, w:CGFloat, h:CGFloat)->UILabel{
var myLabel : UILabel = UILabel(frame: CGRectMake(x,y,w,h))
myLabel.textAlignment = NSTextAlignment.Right
// inser last char to right
var titlePlus1char = "(title)1"
myLabel.text = titlePlus1char
var titleSize:Int = count(titlePlus1char)-1
myLabel.textColor = UIColor(red:1.0, green:1.0,blue:1.0,alpha:1.0)
myLabel.backgroundColor = UIColor(red: 214/255, green: 167/255, blue: 0/255,alpha:1.0)
// create myMutable String
var myMutableString = NSMutableAttributedString()
// create myMutable font
myMutableString = NSMutableAttributedString(string: titlePlus1char, attributes: [NSFontAttributeName:UIFont(name: "HelveticaNeue", size: 20)!])
// set margin size
myMutableString.addAttribute(NSFontAttributeName, value: UIFont(name: "HelveticaNeue", size: 10)!, range: NSRange(location: titleSize,length: 1))
// set last char to alpha 0
myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor(red:1.0, green:1.0,blue:1.0,alpha:0), range: NSRange(location: titleSize,length: 1))
myLabel.attributedText = myMutableString
return myLabel
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
add a comment |
up vote
1
down vote
If you want to add 2px padding around the textRect, just do this:
let insets = UIEdgeInsets(top: -2, left: -2, bottom: -2, right: -2)
label.frame = UIEdgeInsetsInsetRect(textRect, insets)
add a comment |
up vote
1
down vote
If you don't want or need to use an @IBInspectable / @IBDesignable UILabel in Storyboard (I think those are rendered too slow anyway), then it is cleaner to use UIEdgeInsets instead of 4 different CGFloats.
Code example for Swift 4.2:
class UIPaddedLabel: UILabel {
var padding = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
public override func drawText(in rect: CGRect) {
super.drawText(in: rect.inset(by: padding))
}
public override var intrinsicContentSize: CGSize {
let size = super.intrinsicContentSize
return CGSize(width: size.width + padding.left + padding.right,
height: size.height + padding.top + padding.bottom)
}
}
add a comment |
up vote
1
down vote
Use this code if you are facing text trimming problem while applying padding.
@IBDesignable class PaddingLabel: UILabel {
@IBInspectable var topInset: CGFloat = 5.0
@IBInspectable var bottomInset: CGFloat = 5.0
@IBInspectable var leftInset: CGFloat = 5.0
@IBInspectable var rightInset: CGFloat = 5.0
override func drawText(in rect: CGRect) {
let insets = UIEdgeInsets.init(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}
override var intrinsicContentSize: CGSize {
var intrinsicSuperViewContentSize = super.intrinsicContentSize
let textWidth = frame.size.width - (self.leftInset + self.rightInset)
let newSize = self.text!.boundingRect(with: CGSize(textWidth, CGFloat.greatestFiniteMagnitude), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName: self.font], context: nil)
intrinsicSuperViewContentSize.height = ceil(newSize.size.height) + self.topInset + self.bottomInset
return intrinsicSuperViewContentSize
}
}
extension CGSize{
init(_ width:CGFloat,_ height:CGFloat) {
self.init(width:width,height:height)
}
}
Thank you for posting, I am looking for a solution regardin padding + trimming. It seems to me your solution breaks label.numberOfLines = 0 which I need. Any workaround?
– Don
Oct 5 at 8:38
add a comment |
up vote
0
down vote
Easy padding:
import UIKit
class NewLabel: UILabel {
override func textRectForBounds(bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
return CGRectInset(self.bounds, CGFloat(15.0), CGFloat(15.0))
}
override func drawRect(rect: CGRect) {
super.drawTextInRect(CGRectInset(self.bounds,CGFloat(5.0), CGFloat(5.0)))
}
}
3.0 version on bottom page
– odemolliens
Oct 10 '16 at 11:59
add a comment |
up vote
0
down vote
Just use autolayout:
let paddedWidth = myLabel.intrinsicContentSize.width + 2 * padding
myLabel.widthAnchor.constraint(equalToConstant: paddedWidth).isActive = true
Done.
add a comment |
up vote
0
down vote
Similar to other answers, but with a func class to setup the padding dinamically:
class UILabelExtendedView: UILabel
{
var topInset: CGFloat = 4.0
var bottomInset: CGFloat = 4.0
var leftInset: CGFloat = 8.0
var rightInset: CGFloat = 8.0
override func drawText(in rect: CGRect)
{
let insets: UIEdgeInsets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}
override public var intrinsicContentSize: CGSize
{
var contentSize = super.intrinsicContentSize
contentSize.height += topInset + bottomInset
contentSize.width += leftInset + rightInset
return contentSize
}
func setPadding(top: CGFloat, left: CGFloat, bottom: CGFloat, right: CGFloat){
self.topInset = top
self.bottomInset = bottom
self.leftInset = left
self.rightInset = right
let insets: UIEdgeInsets = UIEdgeInsets(top: top, left: left, bottom: bottom, right: right)
super.drawText(in: UIEdgeInsetsInsetRect(self.frame, insets))
}
}
add a comment |
up vote
0
down vote
One pragmatic solution is to add blank labels of the same height and color as the main label. Set the leading/trailing space to the main label to zero, align vertical centers, and make the width your desired margin.
add a comment |
up vote
0
down vote
An elaboration on Mundi's answer.
i.e. embedding a label in a UIView and enforcing padding through Auto Layout. Example:

Overview:
1) Create a UIView ("panel"), and set its appearance.
2) Create a UILabel and add it to the panel.
3) Add constraints to enforce padding.
4) Add the panel to your view hierarchy, then position the panel.
Details:
1) Create the panel view.
let panel = UIView()
panel.backgroundColor = .green
panel.layer.cornerRadius = 12
2) Create the label, add it to the panel as a subview.
let label = UILabel()
panel.addSubview(label)
3) Add constraints between the edges of the label and the panel. This forces the panel to keep a distance from the label. i.e. "padding"
Editorial: doing all this by hand is super-tedious, verbose and error-prone. I suggest you pick an Auto Layout wrapper from github or write one yourself
label.panel.translatesAutoresizingMaskIntoConstraints = false
label.topAnchor.constraint(equalTo: panel.topAnchor,
constant: vPadding).isActive = true
label.bottomAnchor.constraint(equalTo: panel.bottomAnchor,
constant: -vPadding).isActive = true
label.leadingAnchor.constraint(equalTo: panel.leadingAnchor,
constant: hPadding).isActive = true
label.trailingAnchor.constraint(equalTo: panel.trailingAnchor,
constant: -hPadding).isActive = true
label.textAlignment = .center
4) Add the panel to your view hierarchy and then add positioning constraints. e.g. hug the right-hand side of a tableViewCell, as in the example image.
Note: you only need to add positional constraints, not dimensional constraints: Auto Layout will solve the layout based on both the intrinsicContentSize of the label and the constraints added earlier.
hostView.addSubview(panel)
panel.translatesAutoresizingMaskIntoConstraints = false
panel.trailingAnchor.constraint(equalTo: hostView.trailingAnchor,
constant: -16).isActive = true
panel.centerYAnchor.constraint(equalTo: hostView.centerYAnchor).isActive = true
add a comment |
up vote
0
down vote
Just like other answers but fix a bug.
When label.width is controlled by auto layout, sometimes text will be cropped.
@IBDesignable
class InsetLabel: UILabel {
@IBInspectable var topInset: CGFloat = 4.0
@IBInspectable var leftInset: CGFloat = 4.0
@IBInspectable var bottomInset: CGFloat = 4.0
@IBInspectable var rightInset: CGFloat = 4.0
var insets: UIEdgeInsets {
get {
return UIEdgeInsets.init(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
}
set {
topInset = newValue.top
leftInset = newValue.left
bottomInset = newValue.bottom
rightInset = newValue.right
}
}
override func sizeThatFits(_ size: CGSize) -> CGSize {
var adjSize = super.sizeThatFits(size)
adjSize.width += leftInset + rightInset
adjSize.height += topInset + bottomInset
return adjSize
}
override var intrinsicContentSize: CGSize {
let systemContentSize = super.intrinsicContentSize
let adjustSize = CGSize(width: systemContentSize.width + leftInset + rightInset, height: systemContentSize.height + topInset + bottomInset)
if adjustSize.width > preferredMaxLayoutWidth && preferredMaxLayoutWidth != 0 {
let constraintSize = CGSize(width: bounds.width - (leftInset + rightInset), height: .greatestFiniteMagnitude)
let newSize = super.sizeThatFits(constraintSize)
return CGSize(width: systemContentSize.width, height: ceil(newSize.height) + topInset + bottomInset)
} else {
return adjustSize
}
}
override func drawText(in rect: CGRect) {
super.drawText(in: rect.inset(by: insets))
}
}
add a comment |
up vote
0
down vote
Swift 4+
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.firstLineHeadIndent = 10
// Swift 4.2++
label.attributedText = NSAttributedString(string: "Your text", attributes: [NSAttributedString.Key.paragraphStyle: paragraphStyle])
// Swift 4.1--
label.attributedText = NSAttributedString(string: "Your text", attributes: [NSAttributedStringKey.paragraphStyle: paragraphStyle])
New contributor
Maksim Gridin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
add a comment |
27 Answers
27
active
oldest
votes
27 Answers
27
active
oldest
votes
active
oldest
votes
active
oldest
votes
up vote
83
down vote
accepted
If you want to stick with UILabel, without subclassing it, Mundi has given you a clear solution.
If alternatively you would be willing to avoid wrapping the UILabel with a UIView, you could use UITextView to enable the use of UIEdgeInsets (padding) or subclass UILabel to support UIEdgeInsets.
Using a UITextView you would only need to provide the insets (OBJ-C):
textView.textContainerInset = UIEdgeInsetsMake(10, 0, 10, 0);
Alternative, if you subclass UILabel, an example to this approach would be overriding the drawTextInRect method
(OBJ-C)
- (void)drawTextInRect:(CGRect)uiLabelRect {
UIEdgeInsets myLabelInsets = {10, 0, 10, 0};
[super drawTextInRect:UIEdgeInsetsInsetRect(uiLabelRect, myLabelInsets)];
}
You could additionally provide your new subclassed UILabel with a insets variable for TOP, LEFT, BOTTOM and RIGHT.
An example code could be:
In .h (OBJ-C)
float topInset, leftInset,bottomInset, rightInset;
In .m (OBJ-C)
- (void)drawTextInRect:(CGRect)uiLabelRect {
[super drawTextInRect:UIEdgeInsetsInsetRect(uiLabelRect, UIEdgeInsetsMake(topInset,leftInset,bottomInset,rightInset))];
}
EDIT #1:
From what I have seen, it seems you have to override the intrinsicContentSize of the UILabel when subclassing it.
So you should override intrinsicContentSize like:
- (CGSize) intrinsicContentSize {
CGSize intrinsicSuperViewContentSize = [super intrinsicContentSize] ;
intrinsicSuperViewContentSize.height += topInset + bottomInset ;
intrinsicSuperViewContentSize.width += leftInset + rightInset ;
return intrinsicSuperViewContentSize ;
}
And add the following method to edit your insets, instead of editing them individually:
- (void) setContentEdgeInsets:(UIEdgeInsets)edgeInsets {
topInset = edgeInsets.top;
leftInset = edgeInsets.left;
rightInset = edgeInsets.right;
bottomInset = edgeInsets.bottom;
[self invalidateIntrinsicContentSize] ;
}
It will update the size of your UILabel to match the edge insets and cover multiline necessity you referred.
Edit #2
After searching a bit I have found this Gist with a IPInsetLabel. If none of those solutions work you could try it out.
Edit #3
There was similar question (duplicate) about this matter.
For a full list of available solutions, see this answer: UILabel text margin
Sorry but I've alreay used: ` override func drawTextInRect(rect: CGRect) { var insets: UIEdgeInsets = UIEdgeInsets(top: 0.0, left: 10.0, bottom: 0.0, right: 10.0) super.drawTextInRect(UIEdgeInsetsInsetRect(rect, insets)) } ` it doesn't work because the result is the same, don't work dynamically..
– Annachiara
Dec 13 '14 at 17:50
Did you tried with a UITextView instead of a UILabel? Or do you really need to use an UILabel?
– nunofmendes
Dec 13 '14 at 21:34
@Annachiara check the edit I've made. See if it works.
– nunofmendes
Dec 14 '14 at 11:54
Ok. Did it work the textview? Sorry for not writing in Swift but I am still in Obj-C mode. My goal with that code was to help you reach some conclusion. Hope it did.
– nunofmendes
Dec 14 '14 at 16:53
Using TextView and some storyboard settings and self.textview.textContainerInset = UIEdgeInsetsMake(0, 10, 10, 10); It finally works ! Thanks !
– Annachiara
Dec 14 '14 at 16:58
|
show 5 more comments
up vote
83
down vote
accepted
If you want to stick with UILabel, without subclassing it, Mundi has given you a clear solution.
If alternatively you would be willing to avoid wrapping the UILabel with a UIView, you could use UITextView to enable the use of UIEdgeInsets (padding) or subclass UILabel to support UIEdgeInsets.
Using a UITextView you would only need to provide the insets (OBJ-C):
textView.textContainerInset = UIEdgeInsetsMake(10, 0, 10, 0);
Alternative, if you subclass UILabel, an example to this approach would be overriding the drawTextInRect method
(OBJ-C)
- (void)drawTextInRect:(CGRect)uiLabelRect {
UIEdgeInsets myLabelInsets = {10, 0, 10, 0};
[super drawTextInRect:UIEdgeInsetsInsetRect(uiLabelRect, myLabelInsets)];
}
You could additionally provide your new subclassed UILabel with a insets variable for TOP, LEFT, BOTTOM and RIGHT.
An example code could be:
In .h (OBJ-C)
float topInset, leftInset,bottomInset, rightInset;
In .m (OBJ-C)
- (void)drawTextInRect:(CGRect)uiLabelRect {
[super drawTextInRect:UIEdgeInsetsInsetRect(uiLabelRect, UIEdgeInsetsMake(topInset,leftInset,bottomInset,rightInset))];
}
EDIT #1:
From what I have seen, it seems you have to override the intrinsicContentSize of the UILabel when subclassing it.
So you should override intrinsicContentSize like:
- (CGSize) intrinsicContentSize {
CGSize intrinsicSuperViewContentSize = [super intrinsicContentSize] ;
intrinsicSuperViewContentSize.height += topInset + bottomInset ;
intrinsicSuperViewContentSize.width += leftInset + rightInset ;
return intrinsicSuperViewContentSize ;
}
And add the following method to edit your insets, instead of editing them individually:
- (void) setContentEdgeInsets:(UIEdgeInsets)edgeInsets {
topInset = edgeInsets.top;
leftInset = edgeInsets.left;
rightInset = edgeInsets.right;
bottomInset = edgeInsets.bottom;
[self invalidateIntrinsicContentSize] ;
}
It will update the size of your UILabel to match the edge insets and cover multiline necessity you referred.
Edit #2
After searching a bit I have found this Gist with a IPInsetLabel. If none of those solutions work you could try it out.
Edit #3
There was similar question (duplicate) about this matter.
For a full list of available solutions, see this answer: UILabel text margin
Sorry but I've alreay used: ` override func drawTextInRect(rect: CGRect) { var insets: UIEdgeInsets = UIEdgeInsets(top: 0.0, left: 10.0, bottom: 0.0, right: 10.0) super.drawTextInRect(UIEdgeInsetsInsetRect(rect, insets)) } ` it doesn't work because the result is the same, don't work dynamically..
– Annachiara
Dec 13 '14 at 17:50
Did you tried with a UITextView instead of a UILabel? Or do you really need to use an UILabel?
– nunofmendes
Dec 13 '14 at 21:34
@Annachiara check the edit I've made. See if it works.
– nunofmendes
Dec 14 '14 at 11:54
Ok. Did it work the textview? Sorry for not writing in Swift but I am still in Obj-C mode. My goal with that code was to help you reach some conclusion. Hope it did.
– nunofmendes
Dec 14 '14 at 16:53
Using TextView and some storyboard settings and self.textview.textContainerInset = UIEdgeInsetsMake(0, 10, 10, 10); It finally works ! Thanks !
– Annachiara
Dec 14 '14 at 16:58
|
show 5 more comments
up vote
83
down vote
accepted
up vote
83
down vote
accepted
If you want to stick with UILabel, without subclassing it, Mundi has given you a clear solution.
If alternatively you would be willing to avoid wrapping the UILabel with a UIView, you could use UITextView to enable the use of UIEdgeInsets (padding) or subclass UILabel to support UIEdgeInsets.
Using a UITextView you would only need to provide the insets (OBJ-C):
textView.textContainerInset = UIEdgeInsetsMake(10, 0, 10, 0);
Alternative, if you subclass UILabel, an example to this approach would be overriding the drawTextInRect method
(OBJ-C)
- (void)drawTextInRect:(CGRect)uiLabelRect {
UIEdgeInsets myLabelInsets = {10, 0, 10, 0};
[super drawTextInRect:UIEdgeInsetsInsetRect(uiLabelRect, myLabelInsets)];
}
You could additionally provide your new subclassed UILabel with a insets variable for TOP, LEFT, BOTTOM and RIGHT.
An example code could be:
In .h (OBJ-C)
float topInset, leftInset,bottomInset, rightInset;
In .m (OBJ-C)
- (void)drawTextInRect:(CGRect)uiLabelRect {
[super drawTextInRect:UIEdgeInsetsInsetRect(uiLabelRect, UIEdgeInsetsMake(topInset,leftInset,bottomInset,rightInset))];
}
EDIT #1:
From what I have seen, it seems you have to override the intrinsicContentSize of the UILabel when subclassing it.
So you should override intrinsicContentSize like:
- (CGSize) intrinsicContentSize {
CGSize intrinsicSuperViewContentSize = [super intrinsicContentSize] ;
intrinsicSuperViewContentSize.height += topInset + bottomInset ;
intrinsicSuperViewContentSize.width += leftInset + rightInset ;
return intrinsicSuperViewContentSize ;
}
And add the following method to edit your insets, instead of editing them individually:
- (void) setContentEdgeInsets:(UIEdgeInsets)edgeInsets {
topInset = edgeInsets.top;
leftInset = edgeInsets.left;
rightInset = edgeInsets.right;
bottomInset = edgeInsets.bottom;
[self invalidateIntrinsicContentSize] ;
}
It will update the size of your UILabel to match the edge insets and cover multiline necessity you referred.
Edit #2
After searching a bit I have found this Gist with a IPInsetLabel. If none of those solutions work you could try it out.
Edit #3
There was similar question (duplicate) about this matter.
For a full list of available solutions, see this answer: UILabel text margin
If you want to stick with UILabel, without subclassing it, Mundi has given you a clear solution.
If alternatively you would be willing to avoid wrapping the UILabel with a UIView, you could use UITextView to enable the use of UIEdgeInsets (padding) or subclass UILabel to support UIEdgeInsets.
Using a UITextView you would only need to provide the insets (OBJ-C):
textView.textContainerInset = UIEdgeInsetsMake(10, 0, 10, 0);
Alternative, if you subclass UILabel, an example to this approach would be overriding the drawTextInRect method
(OBJ-C)
- (void)drawTextInRect:(CGRect)uiLabelRect {
UIEdgeInsets myLabelInsets = {10, 0, 10, 0};
[super drawTextInRect:UIEdgeInsetsInsetRect(uiLabelRect, myLabelInsets)];
}
You could additionally provide your new subclassed UILabel with a insets variable for TOP, LEFT, BOTTOM and RIGHT.
An example code could be:
In .h (OBJ-C)
float topInset, leftInset,bottomInset, rightInset;
In .m (OBJ-C)
- (void)drawTextInRect:(CGRect)uiLabelRect {
[super drawTextInRect:UIEdgeInsetsInsetRect(uiLabelRect, UIEdgeInsetsMake(topInset,leftInset,bottomInset,rightInset))];
}
EDIT #1:
From what I have seen, it seems you have to override the intrinsicContentSize of the UILabel when subclassing it.
So you should override intrinsicContentSize like:
- (CGSize) intrinsicContentSize {
CGSize intrinsicSuperViewContentSize = [super intrinsicContentSize] ;
intrinsicSuperViewContentSize.height += topInset + bottomInset ;
intrinsicSuperViewContentSize.width += leftInset + rightInset ;
return intrinsicSuperViewContentSize ;
}
And add the following method to edit your insets, instead of editing them individually:
- (void) setContentEdgeInsets:(UIEdgeInsets)edgeInsets {
topInset = edgeInsets.top;
leftInset = edgeInsets.left;
rightInset = edgeInsets.right;
bottomInset = edgeInsets.bottom;
[self invalidateIntrinsicContentSize] ;
}
It will update the size of your UILabel to match the edge insets and cover multiline necessity you referred.
Edit #2
After searching a bit I have found this Gist with a IPInsetLabel. If none of those solutions work you could try it out.
Edit #3
There was similar question (duplicate) about this matter.
For a full list of available solutions, see this answer: UILabel text margin
edited May 23 '17 at 12:26
Community♦
11
11
answered Dec 13 '14 at 16:31
nunofmendes
2,68412336
2,68412336
Sorry but I've alreay used: ` override func drawTextInRect(rect: CGRect) { var insets: UIEdgeInsets = UIEdgeInsets(top: 0.0, left: 10.0, bottom: 0.0, right: 10.0) super.drawTextInRect(UIEdgeInsetsInsetRect(rect, insets)) } ` it doesn't work because the result is the same, don't work dynamically..
– Annachiara
Dec 13 '14 at 17:50
Did you tried with a UITextView instead of a UILabel? Or do you really need to use an UILabel?
– nunofmendes
Dec 13 '14 at 21:34
@Annachiara check the edit I've made. See if it works.
– nunofmendes
Dec 14 '14 at 11:54
Ok. Did it work the textview? Sorry for not writing in Swift but I am still in Obj-C mode. My goal with that code was to help you reach some conclusion. Hope it did.
– nunofmendes
Dec 14 '14 at 16:53
Using TextView and some storyboard settings and self.textview.textContainerInset = UIEdgeInsetsMake(0, 10, 10, 10); It finally works ! Thanks !
– Annachiara
Dec 14 '14 at 16:58
|
show 5 more comments
Sorry but I've alreay used: ` override func drawTextInRect(rect: CGRect) { var insets: UIEdgeInsets = UIEdgeInsets(top: 0.0, left: 10.0, bottom: 0.0, right: 10.0) super.drawTextInRect(UIEdgeInsetsInsetRect(rect, insets)) } ` it doesn't work because the result is the same, don't work dynamically..
– Annachiara
Dec 13 '14 at 17:50
Did you tried with a UITextView instead of a UILabel? Or do you really need to use an UILabel?
– nunofmendes
Dec 13 '14 at 21:34
@Annachiara check the edit I've made. See if it works.
– nunofmendes
Dec 14 '14 at 11:54
Ok. Did it work the textview? Sorry for not writing in Swift but I am still in Obj-C mode. My goal with that code was to help you reach some conclusion. Hope it did.
– nunofmendes
Dec 14 '14 at 16:53
Using TextView and some storyboard settings and self.textview.textContainerInset = UIEdgeInsetsMake(0, 10, 10, 10); It finally works ! Thanks !
– Annachiara
Dec 14 '14 at 16:58
Sorry but I've alreay used: ` override func drawTextInRect(rect: CGRect) { var insets: UIEdgeInsets = UIEdgeInsets(top: 0.0, left: 10.0, bottom: 0.0, right: 10.0) super.drawTextInRect(UIEdgeInsetsInsetRect(rect, insets)) } ` it doesn't work because the result is the same, don't work dynamically..
– Annachiara
Dec 13 '14 at 17:50
Sorry but I've alreay used: ` override func drawTextInRect(rect: CGRect) { var insets: UIEdgeInsets = UIEdgeInsets(top: 0.0, left: 10.0, bottom: 0.0, right: 10.0) super.drawTextInRect(UIEdgeInsetsInsetRect(rect, insets)) } ` it doesn't work because the result is the same, don't work dynamically..
– Annachiara
Dec 13 '14 at 17:50
Did you tried with a UITextView instead of a UILabel? Or do you really need to use an UILabel?
– nunofmendes
Dec 13 '14 at 21:34
Did you tried with a UITextView instead of a UILabel? Or do you really need to use an UILabel?
– nunofmendes
Dec 13 '14 at 21:34
@Annachiara check the edit I've made. See if it works.
– nunofmendes
Dec 14 '14 at 11:54
@Annachiara check the edit I've made. See if it works.
– nunofmendes
Dec 14 '14 at 11:54
Ok. Did it work the textview? Sorry for not writing in Swift but I am still in Obj-C mode. My goal with that code was to help you reach some conclusion. Hope it did.
– nunofmendes
Dec 14 '14 at 16:53
Ok. Did it work the textview? Sorry for not writing in Swift but I am still in Obj-C mode. My goal with that code was to help you reach some conclusion. Hope it did.
– nunofmendes
Dec 14 '14 at 16:53
Using TextView and some storyboard settings and self.textview.textContainerInset = UIEdgeInsetsMake(0, 10, 10, 10); It finally works ! Thanks !
– Annachiara
Dec 14 '14 at 16:58
Using TextView and some storyboard settings and self.textview.textContainerInset = UIEdgeInsetsMake(0, 10, 10, 10); It finally works ! Thanks !
– Annachiara
Dec 14 '14 at 16:58
|
show 5 more comments
up vote
109
down vote
I have tried with it on Swift 4.2, hopefully it work for you!
@IBDesignable class PaddingLabel: UILabel {
@IBInspectable var topInset: CGFloat = 5.0
@IBInspectable var bottomInset: CGFloat = 5.0
@IBInspectable var leftInset: CGFloat = 7.0
@IBInspectable var rightInset: CGFloat = 7.0
override func drawText(in rect: CGRect) {
let insets = UIEdgeInsets.init(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawText(in: rect.inset(by: insets))
}
override var intrinsicContentSize: CGSize {
let size = super.intrinsicContentSize
return CGSize(width: size.width + leftInset + rightInset,
height: size.height + topInset + bottomInset)
}
}
Or you can use CocoaPods here https://github.com/levantAJ/PaddingLabel
pod 'PaddingLabel', '1.1'
1
This worked so well! Thanks, mate. Cheers.
– Felipe
May 3 at 6:53
this worked pretty good, thank you!
– Wilson
May 8 at 21:28
2
The uilabel width is not changing, causing the text become "..."
– neobie
May 12 at 6:09
1
@Tai Le , thanks for sharing, I have used it in tableview, I don't know why its triming the text , eg. student becomes studen,
– vishwa.deepak
Aug 30 at 6:04
1
Changing the return statement toreturn CGSize(width: max(size.width + leftInset + rightInset, 10000), height: size.height + topInset + bottomInset)solved the issue, just FYI!
– Tim
Nov 10 at 16:16
|
show 3 more comments
up vote
109
down vote
I have tried with it on Swift 4.2, hopefully it work for you!
@IBDesignable class PaddingLabel: UILabel {
@IBInspectable var topInset: CGFloat = 5.0
@IBInspectable var bottomInset: CGFloat = 5.0
@IBInspectable var leftInset: CGFloat = 7.0
@IBInspectable var rightInset: CGFloat = 7.0
override func drawText(in rect: CGRect) {
let insets = UIEdgeInsets.init(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawText(in: rect.inset(by: insets))
}
override var intrinsicContentSize: CGSize {
let size = super.intrinsicContentSize
return CGSize(width: size.width + leftInset + rightInset,
height: size.height + topInset + bottomInset)
}
}
Or you can use CocoaPods here https://github.com/levantAJ/PaddingLabel
pod 'PaddingLabel', '1.1'
1
This worked so well! Thanks, mate. Cheers.
– Felipe
May 3 at 6:53
this worked pretty good, thank you!
– Wilson
May 8 at 21:28
2
The uilabel width is not changing, causing the text become "..."
– neobie
May 12 at 6:09
1
@Tai Le , thanks for sharing, I have used it in tableview, I don't know why its triming the text , eg. student becomes studen,
– vishwa.deepak
Aug 30 at 6:04
1
Changing the return statement toreturn CGSize(width: max(size.width + leftInset + rightInset, 10000), height: size.height + topInset + bottomInset)solved the issue, just FYI!
– Tim
Nov 10 at 16:16
|
show 3 more comments
up vote
109
down vote
up vote
109
down vote
I have tried with it on Swift 4.2, hopefully it work for you!
@IBDesignable class PaddingLabel: UILabel {
@IBInspectable var topInset: CGFloat = 5.0
@IBInspectable var bottomInset: CGFloat = 5.0
@IBInspectable var leftInset: CGFloat = 7.0
@IBInspectable var rightInset: CGFloat = 7.0
override func drawText(in rect: CGRect) {
let insets = UIEdgeInsets.init(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawText(in: rect.inset(by: insets))
}
override var intrinsicContentSize: CGSize {
let size = super.intrinsicContentSize
return CGSize(width: size.width + leftInset + rightInset,
height: size.height + topInset + bottomInset)
}
}
Or you can use CocoaPods here https://github.com/levantAJ/PaddingLabel
pod 'PaddingLabel', '1.1'
I have tried with it on Swift 4.2, hopefully it work for you!
@IBDesignable class PaddingLabel: UILabel {
@IBInspectable var topInset: CGFloat = 5.0
@IBInspectable var bottomInset: CGFloat = 5.0
@IBInspectable var leftInset: CGFloat = 7.0
@IBInspectable var rightInset: CGFloat = 7.0
override func drawText(in rect: CGRect) {
let insets = UIEdgeInsets.init(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawText(in: rect.inset(by: insets))
}
override var intrinsicContentSize: CGSize {
let size = super.intrinsicContentSize
return CGSize(width: size.width + leftInset + rightInset,
height: size.height + topInset + bottomInset)
}
}
Or you can use CocoaPods here https://github.com/levantAJ/PaddingLabel
pod 'PaddingLabel', '1.1'
edited Nov 24 at 9:24
answered Sep 3 '15 at 7:00
Tai Le
2,61712319
2,61712319
1
This worked so well! Thanks, mate. Cheers.
– Felipe
May 3 at 6:53
this worked pretty good, thank you!
– Wilson
May 8 at 21:28
2
The uilabel width is not changing, causing the text become "..."
– neobie
May 12 at 6:09
1
@Tai Le , thanks for sharing, I have used it in tableview, I don't know why its triming the text , eg. student becomes studen,
– vishwa.deepak
Aug 30 at 6:04
1
Changing the return statement toreturn CGSize(width: max(size.width + leftInset + rightInset, 10000), height: size.height + topInset + bottomInset)solved the issue, just FYI!
– Tim
Nov 10 at 16:16
|
show 3 more comments
1
This worked so well! Thanks, mate. Cheers.
– Felipe
May 3 at 6:53
this worked pretty good, thank you!
– Wilson
May 8 at 21:28
2
The uilabel width is not changing, causing the text become "..."
– neobie
May 12 at 6:09
1
@Tai Le , thanks for sharing, I have used it in tableview, I don't know why its triming the text , eg. student becomes studen,
– vishwa.deepak
Aug 30 at 6:04
1
Changing the return statement toreturn CGSize(width: max(size.width + leftInset + rightInset, 10000), height: size.height + topInset + bottomInset)solved the issue, just FYI!
– Tim
Nov 10 at 16:16
1
1
This worked so well! Thanks, mate. Cheers.
– Felipe
May 3 at 6:53
This worked so well! Thanks, mate. Cheers.
– Felipe
May 3 at 6:53
this worked pretty good, thank you!
– Wilson
May 8 at 21:28
this worked pretty good, thank you!
– Wilson
May 8 at 21:28
2
2
The uilabel width is not changing, causing the text become "..."
– neobie
May 12 at 6:09
The uilabel width is not changing, causing the text become "..."
– neobie
May 12 at 6:09
1
1
@Tai Le , thanks for sharing, I have used it in tableview, I don't know why its triming the text , eg. student becomes studen,
– vishwa.deepak
Aug 30 at 6:04
@Tai Le , thanks for sharing, I have used it in tableview, I don't know why its triming the text , eg. student becomes studen,
– vishwa.deepak
Aug 30 at 6:04
1
1
Changing the return statement to
return CGSize(width: max(size.width + leftInset + rightInset, 10000), height: size.height + topInset + bottomInset) solved the issue, just FYI!– Tim
Nov 10 at 16:16
Changing the return statement to
return CGSize(width: max(size.width + leftInset + rightInset, 10000), height: size.height + topInset + bottomInset) solved the issue, just FYI!– Tim
Nov 10 at 16:16
|
show 3 more comments
up vote
70
down vote
Swift 3
import UIKit
class PaddingLabel: UILabel {
@IBInspectable var topInset: CGFloat = 5.0
@IBInspectable var bottomInset: CGFloat = 5.0
@IBInspectable var leftInset: CGFloat = 5.0
@IBInspectable var rightInset: CGFloat = 5.0
override func drawText(in rect: CGRect) {
let insets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}
override var intrinsicContentSize: CGSize {
get {
var contentSize = super.intrinsicContentSize
contentSize.height += topInset + bottomInset
contentSize.width += leftInset + rightInset
return contentSize
}
}
}
just a little comment: set this class to label in identity inspector(custom class) and use new attribute in attribute inspector named label padding. also below 5 padding is effectless
– iman kazemayni
Jan 23 at 10:48
This doesn't always work correctly with multiline labels, because when the label calculates its height, it assumes zero padding.
– fhucho
Feb 22 at 16:37
add a comment |
up vote
70
down vote
Swift 3
import UIKit
class PaddingLabel: UILabel {
@IBInspectable var topInset: CGFloat = 5.0
@IBInspectable var bottomInset: CGFloat = 5.0
@IBInspectable var leftInset: CGFloat = 5.0
@IBInspectable var rightInset: CGFloat = 5.0
override func drawText(in rect: CGRect) {
let insets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}
override var intrinsicContentSize: CGSize {
get {
var contentSize = super.intrinsicContentSize
contentSize.height += topInset + bottomInset
contentSize.width += leftInset + rightInset
return contentSize
}
}
}
just a little comment: set this class to label in identity inspector(custom class) and use new attribute in attribute inspector named label padding. also below 5 padding is effectless
– iman kazemayni
Jan 23 at 10:48
This doesn't always work correctly with multiline labels, because when the label calculates its height, it assumes zero padding.
– fhucho
Feb 22 at 16:37
add a comment |
up vote
70
down vote
up vote
70
down vote
Swift 3
import UIKit
class PaddingLabel: UILabel {
@IBInspectable var topInset: CGFloat = 5.0
@IBInspectable var bottomInset: CGFloat = 5.0
@IBInspectable var leftInset: CGFloat = 5.0
@IBInspectable var rightInset: CGFloat = 5.0
override func drawText(in rect: CGRect) {
let insets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}
override var intrinsicContentSize: CGSize {
get {
var contentSize = super.intrinsicContentSize
contentSize.height += topInset + bottomInset
contentSize.width += leftInset + rightInset
return contentSize
}
}
}
Swift 3
import UIKit
class PaddingLabel: UILabel {
@IBInspectable var topInset: CGFloat = 5.0
@IBInspectable var bottomInset: CGFloat = 5.0
@IBInspectable var leftInset: CGFloat = 5.0
@IBInspectable var rightInset: CGFloat = 5.0
override func drawText(in rect: CGRect) {
let insets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}
override var intrinsicContentSize: CGSize {
get {
var contentSize = super.intrinsicContentSize
contentSize.height += topInset + bottomInset
contentSize.width += leftInset + rightInset
return contentSize
}
}
}
edited Nov 12 '16 at 16:17
Gabriel.Massana
6,60654973
6,60654973
answered Oct 12 '16 at 12:12
zombie
2,73021030
2,73021030
just a little comment: set this class to label in identity inspector(custom class) and use new attribute in attribute inspector named label padding. also below 5 padding is effectless
– iman kazemayni
Jan 23 at 10:48
This doesn't always work correctly with multiline labels, because when the label calculates its height, it assumes zero padding.
– fhucho
Feb 22 at 16:37
add a comment |
just a little comment: set this class to label in identity inspector(custom class) and use new attribute in attribute inspector named label padding. also below 5 padding is effectless
– iman kazemayni
Jan 23 at 10:48
This doesn't always work correctly with multiline labels, because when the label calculates its height, it assumes zero padding.
– fhucho
Feb 22 at 16:37
just a little comment: set this class to label in identity inspector(custom class) and use new attribute in attribute inspector named label padding. also below 5 padding is effectless
– iman kazemayni
Jan 23 at 10:48
just a little comment: set this class to label in identity inspector(custom class) and use new attribute in attribute inspector named label padding. also below 5 padding is effectless
– iman kazemayni
Jan 23 at 10:48
This doesn't always work correctly with multiline labels, because when the label calculates its height, it assumes zero padding.
– fhucho
Feb 22 at 16:37
This doesn't always work correctly with multiline labels, because when the label calculates its height, it assumes zero padding.
– fhucho
Feb 22 at 16:37
add a comment |
up vote
61
down vote
You can do it properly from IB :
- change the text to attributed

- go to dropdown list with "..."

- you will see some padding properties for the lines, paragraphs and text change indent first line or anything you want

- check the result

1
In my storyboard I can see the text change but when I run the app. The text doesn´t show the change... T_T.. my label is inside of an custom cell, are there any problem?
– A. Trejo
Feb 17 '16 at 20:11
1
@A.Trejo May be your custom cell set the label property at run time.
– Pierre-Yves Guillemet
Feb 19 '16 at 9:05
In SB right margin can't has negative value. Do it in code.style.tailIndent = -30.0. Still can't do top and bottom indent.
– Nik Kov
Nov 25 '16 at 5:41
1
Changes can appear on storyboard but when you run the app there are no changes.
– Rhenz
May 30 '17 at 2:41
1
This is not applicable when you set text programatically.
– Nij
Jul 16 at 11:43
add a comment |
up vote
61
down vote
You can do it properly from IB :
- change the text to attributed

- go to dropdown list with "..."

- you will see some padding properties for the lines, paragraphs and text change indent first line or anything you want

- check the result

1
In my storyboard I can see the text change but when I run the app. The text doesn´t show the change... T_T.. my label is inside of an custom cell, are there any problem?
– A. Trejo
Feb 17 '16 at 20:11
1
@A.Trejo May be your custom cell set the label property at run time.
– Pierre-Yves Guillemet
Feb 19 '16 at 9:05
In SB right margin can't has negative value. Do it in code.style.tailIndent = -30.0. Still can't do top and bottom indent.
– Nik Kov
Nov 25 '16 at 5:41
1
Changes can appear on storyboard but when you run the app there are no changes.
– Rhenz
May 30 '17 at 2:41
1
This is not applicable when you set text programatically.
– Nij
Jul 16 at 11:43
add a comment |
up vote
61
down vote
up vote
61
down vote
You can do it properly from IB :
- change the text to attributed

- go to dropdown list with "..."

- you will see some padding properties for the lines, paragraphs and text change indent first line or anything you want

- check the result

You can do it properly from IB :
- change the text to attributed

- go to dropdown list with "..."

- you will see some padding properties for the lines, paragraphs and text change indent first line or anything you want

- check the result

answered Sep 12 '15 at 10:23
Pierre-Yves Guillemet
2,11111111
2,11111111
1
In my storyboard I can see the text change but when I run the app. The text doesn´t show the change... T_T.. my label is inside of an custom cell, are there any problem?
– A. Trejo
Feb 17 '16 at 20:11
1
@A.Trejo May be your custom cell set the label property at run time.
– Pierre-Yves Guillemet
Feb 19 '16 at 9:05
In SB right margin can't has negative value. Do it in code.style.tailIndent = -30.0. Still can't do top and bottom indent.
– Nik Kov
Nov 25 '16 at 5:41
1
Changes can appear on storyboard but when you run the app there are no changes.
– Rhenz
May 30 '17 at 2:41
1
This is not applicable when you set text programatically.
– Nij
Jul 16 at 11:43
add a comment |
1
In my storyboard I can see the text change but when I run the app. The text doesn´t show the change... T_T.. my label is inside of an custom cell, are there any problem?
– A. Trejo
Feb 17 '16 at 20:11
1
@A.Trejo May be your custom cell set the label property at run time.
– Pierre-Yves Guillemet
Feb 19 '16 at 9:05
In SB right margin can't has negative value. Do it in code.style.tailIndent = -30.0. Still can't do top and bottom indent.
– Nik Kov
Nov 25 '16 at 5:41
1
Changes can appear on storyboard but when you run the app there are no changes.
– Rhenz
May 30 '17 at 2:41
1
This is not applicable when you set text programatically.
– Nij
Jul 16 at 11:43
1
1
In my storyboard I can see the text change but when I run the app. The text doesn´t show the change... T_T.. my label is inside of an custom cell, are there any problem?
– A. Trejo
Feb 17 '16 at 20:11
In my storyboard I can see the text change but when I run the app. The text doesn´t show the change... T_T.. my label is inside of an custom cell, are there any problem?
– A. Trejo
Feb 17 '16 at 20:11
1
1
@A.Trejo May be your custom cell set the label property at run time.
– Pierre-Yves Guillemet
Feb 19 '16 at 9:05
@A.Trejo May be your custom cell set the label property at run time.
– Pierre-Yves Guillemet
Feb 19 '16 at 9:05
In SB right margin can't has negative value. Do it in code.
style.tailIndent = -30.0. Still can't do top and bottom indent.– Nik Kov
Nov 25 '16 at 5:41
In SB right margin can't has negative value. Do it in code.
style.tailIndent = -30.0. Still can't do top and bottom indent.– Nik Kov
Nov 25 '16 at 5:41
1
1
Changes can appear on storyboard but when you run the app there are no changes.
– Rhenz
May 30 '17 at 2:41
Changes can appear on storyboard but when you run the app there are no changes.
– Rhenz
May 30 '17 at 2:41
1
1
This is not applicable when you set text programatically.
– Nij
Jul 16 at 11:43
This is not applicable when you set text programatically.
– Nij
Jul 16 at 11:43
add a comment |
up vote
33
down vote
SWIFT 3/4
Easy to use solution, available for all UILabel child in project.
Example:
let label = UILabel()
label.<Do something>
label.padding = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 0)
UILabel Extension
import UIKit
extension UILabel {
private struct AssociatedKeys {
static var padding = UIEdgeInsets()
}
public var padding: UIEdgeInsets? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.padding) as? UIEdgeInsets
}
set {
if let newValue = newValue {
objc_setAssociatedObject(self, &AssociatedKeys.padding, newValue as UIEdgeInsets!, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
override open func draw(_ rect: CGRect) {
if let insets = padding {
self.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
} else {
self.drawText(in: rect)
}
}
override open var intrinsicContentSize: CGSize {
guard let text = self.text else { return super.intrinsicContentSize }
var contentSize = super.intrinsicContentSize
var textWidth: CGFloat = frame.size.width
var insetsHeight: CGFloat = 0.0
if let insets = padding {
textWidth -= insets.left + insets.right
insetsHeight += insets.top + insets.bottom
}
let newSize = text.boundingRect(with: CGSize(width: textWidth, height: CGFloat.greatestFiniteMagnitude),
options: NSStringDrawingOptions.usesLineFragmentOrigin,
attributes: [NSAttributedStringKey.font: self.font], context: nil)
contentSize.height = ceil(newSize.size.height) + insetsHeight
return contentSize
}
}
please briefly explain your answer, and do not only post code.
– lmiguelvargasf
May 24 '17 at 1:27
5
Nice solution. I think the code is self-explanatory.
– Jano
Jul 21 '17 at 8:16
4
Your extension cancel the 0 value to numberOfLines
– Antoine Bodart
Aug 4 '17 at 14:09
This is great, but Im having issues with multiple lines, even thought I add numbers of lines 2 or leave at 0, it always shows one. you know how to solve it?
– Mago Nicolas Palacios
Nov 8 '17 at 14:14
1
@AntoineBodart did you manage to solve the numberOfLines problem?
– Mago Nicolas Palacios
Nov 8 '17 at 14:14
|
show 7 more comments
up vote
33
down vote
SWIFT 3/4
Easy to use solution, available for all UILabel child in project.
Example:
let label = UILabel()
label.<Do something>
label.padding = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 0)
UILabel Extension
import UIKit
extension UILabel {
private struct AssociatedKeys {
static var padding = UIEdgeInsets()
}
public var padding: UIEdgeInsets? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.padding) as? UIEdgeInsets
}
set {
if let newValue = newValue {
objc_setAssociatedObject(self, &AssociatedKeys.padding, newValue as UIEdgeInsets!, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
override open func draw(_ rect: CGRect) {
if let insets = padding {
self.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
} else {
self.drawText(in: rect)
}
}
override open var intrinsicContentSize: CGSize {
guard let text = self.text else { return super.intrinsicContentSize }
var contentSize = super.intrinsicContentSize
var textWidth: CGFloat = frame.size.width
var insetsHeight: CGFloat = 0.0
if let insets = padding {
textWidth -= insets.left + insets.right
insetsHeight += insets.top + insets.bottom
}
let newSize = text.boundingRect(with: CGSize(width: textWidth, height: CGFloat.greatestFiniteMagnitude),
options: NSStringDrawingOptions.usesLineFragmentOrigin,
attributes: [NSAttributedStringKey.font: self.font], context: nil)
contentSize.height = ceil(newSize.size.height) + insetsHeight
return contentSize
}
}
please briefly explain your answer, and do not only post code.
– lmiguelvargasf
May 24 '17 at 1:27
5
Nice solution. I think the code is self-explanatory.
– Jano
Jul 21 '17 at 8:16
4
Your extension cancel the 0 value to numberOfLines
– Antoine Bodart
Aug 4 '17 at 14:09
This is great, but Im having issues with multiple lines, even thought I add numbers of lines 2 or leave at 0, it always shows one. you know how to solve it?
– Mago Nicolas Palacios
Nov 8 '17 at 14:14
1
@AntoineBodart did you manage to solve the numberOfLines problem?
– Mago Nicolas Palacios
Nov 8 '17 at 14:14
|
show 7 more comments
up vote
33
down vote
up vote
33
down vote
SWIFT 3/4
Easy to use solution, available for all UILabel child in project.
Example:
let label = UILabel()
label.<Do something>
label.padding = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 0)
UILabel Extension
import UIKit
extension UILabel {
private struct AssociatedKeys {
static var padding = UIEdgeInsets()
}
public var padding: UIEdgeInsets? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.padding) as? UIEdgeInsets
}
set {
if let newValue = newValue {
objc_setAssociatedObject(self, &AssociatedKeys.padding, newValue as UIEdgeInsets!, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
override open func draw(_ rect: CGRect) {
if let insets = padding {
self.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
} else {
self.drawText(in: rect)
}
}
override open var intrinsicContentSize: CGSize {
guard let text = self.text else { return super.intrinsicContentSize }
var contentSize = super.intrinsicContentSize
var textWidth: CGFloat = frame.size.width
var insetsHeight: CGFloat = 0.0
if let insets = padding {
textWidth -= insets.left + insets.right
insetsHeight += insets.top + insets.bottom
}
let newSize = text.boundingRect(with: CGSize(width: textWidth, height: CGFloat.greatestFiniteMagnitude),
options: NSStringDrawingOptions.usesLineFragmentOrigin,
attributes: [NSAttributedStringKey.font: self.font], context: nil)
contentSize.height = ceil(newSize.size.height) + insetsHeight
return contentSize
}
}
SWIFT 3/4
Easy to use solution, available for all UILabel child in project.
Example:
let label = UILabel()
label.<Do something>
label.padding = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 0)
UILabel Extension
import UIKit
extension UILabel {
private struct AssociatedKeys {
static var padding = UIEdgeInsets()
}
public var padding: UIEdgeInsets? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.padding) as? UIEdgeInsets
}
set {
if let newValue = newValue {
objc_setAssociatedObject(self, &AssociatedKeys.padding, newValue as UIEdgeInsets!, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
override open func draw(_ rect: CGRect) {
if let insets = padding {
self.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
} else {
self.drawText(in: rect)
}
}
override open var intrinsicContentSize: CGSize {
guard let text = self.text else { return super.intrinsicContentSize }
var contentSize = super.intrinsicContentSize
var textWidth: CGFloat = frame.size.width
var insetsHeight: CGFloat = 0.0
if let insets = padding {
textWidth -= insets.left + insets.right
insetsHeight += insets.top + insets.bottom
}
let newSize = text.boundingRect(with: CGSize(width: textWidth, height: CGFloat.greatestFiniteMagnitude),
options: NSStringDrawingOptions.usesLineFragmentOrigin,
attributes: [NSAttributedStringKey.font: self.font], context: nil)
contentSize.height = ceil(newSize.size.height) + insetsHeight
return contentSize
}
}
edited Mar 8 at 0:14
answered May 23 '17 at 22:11
podkorytov
44945
44945
please briefly explain your answer, and do not only post code.
– lmiguelvargasf
May 24 '17 at 1:27
5
Nice solution. I think the code is self-explanatory.
– Jano
Jul 21 '17 at 8:16
4
Your extension cancel the 0 value to numberOfLines
– Antoine Bodart
Aug 4 '17 at 14:09
This is great, but Im having issues with multiple lines, even thought I add numbers of lines 2 or leave at 0, it always shows one. you know how to solve it?
– Mago Nicolas Palacios
Nov 8 '17 at 14:14
1
@AntoineBodart did you manage to solve the numberOfLines problem?
– Mago Nicolas Palacios
Nov 8 '17 at 14:14
|
show 7 more comments
please briefly explain your answer, and do not only post code.
– lmiguelvargasf
May 24 '17 at 1:27
5
Nice solution. I think the code is self-explanatory.
– Jano
Jul 21 '17 at 8:16
4
Your extension cancel the 0 value to numberOfLines
– Antoine Bodart
Aug 4 '17 at 14:09
This is great, but Im having issues with multiple lines, even thought I add numbers of lines 2 or leave at 0, it always shows one. you know how to solve it?
– Mago Nicolas Palacios
Nov 8 '17 at 14:14
1
@AntoineBodart did you manage to solve the numberOfLines problem?
– Mago Nicolas Palacios
Nov 8 '17 at 14:14
please briefly explain your answer, and do not only post code.
– lmiguelvargasf
May 24 '17 at 1:27
please briefly explain your answer, and do not only post code.
– lmiguelvargasf
May 24 '17 at 1:27
5
5
Nice solution. I think the code is self-explanatory.
– Jano
Jul 21 '17 at 8:16
Nice solution. I think the code is self-explanatory.
– Jano
Jul 21 '17 at 8:16
4
4
Your extension cancel the 0 value to numberOfLines
– Antoine Bodart
Aug 4 '17 at 14:09
Your extension cancel the 0 value to numberOfLines
– Antoine Bodart
Aug 4 '17 at 14:09
This is great, but Im having issues with multiple lines, even thought I add numbers of lines 2 or leave at 0, it always shows one. you know how to solve it?
– Mago Nicolas Palacios
Nov 8 '17 at 14:14
This is great, but Im having issues with multiple lines, even thought I add numbers of lines 2 or leave at 0, it always shows one. you know how to solve it?
– Mago Nicolas Palacios
Nov 8 '17 at 14:14
1
1
@AntoineBodart did you manage to solve the numberOfLines problem?
– Mago Nicolas Palacios
Nov 8 '17 at 14:14
@AntoineBodart did you manage to solve the numberOfLines problem?
– Mago Nicolas Palacios
Nov 8 '17 at 14:14
|
show 7 more comments
up vote
32
down vote
Just use a UIView as a superview and define a fixed margin to the label with auto layout.
1
drawTextInRectworks only for 1 line,intrinsicContentSizedoes not work with horizontal padding. Wrap UILabel inside UIView is the good way to go
– onmyway133
Jun 3 '15 at 8:31
4
If you're in IB, now is the time to remember the menu Editor -> Embed In -> View. Just select your UILabel first :)
– Graham Perks
Apr 26 '17 at 18:58
add a comment |
up vote
32
down vote
Just use a UIView as a superview and define a fixed margin to the label with auto layout.
1
drawTextInRectworks only for 1 line,intrinsicContentSizedoes not work with horizontal padding. Wrap UILabel inside UIView is the good way to go
– onmyway133
Jun 3 '15 at 8:31
4
If you're in IB, now is the time to remember the menu Editor -> Embed In -> View. Just select your UILabel first :)
– Graham Perks
Apr 26 '17 at 18:58
add a comment |
up vote
32
down vote
up vote
32
down vote
Just use a UIView as a superview and define a fixed margin to the label with auto layout.
Just use a UIView as a superview and define a fixed margin to the label with auto layout.
answered Dec 13 '14 at 16:20
Mundi
69.3k1693120
69.3k1693120
1
drawTextInRectworks only for 1 line,intrinsicContentSizedoes not work with horizontal padding. Wrap UILabel inside UIView is the good way to go
– onmyway133
Jun 3 '15 at 8:31
4
If you're in IB, now is the time to remember the menu Editor -> Embed In -> View. Just select your UILabel first :)
– Graham Perks
Apr 26 '17 at 18:58
add a comment |
1
drawTextInRectworks only for 1 line,intrinsicContentSizedoes not work with horizontal padding. Wrap UILabel inside UIView is the good way to go
– onmyway133
Jun 3 '15 at 8:31
4
If you're in IB, now is the time to remember the menu Editor -> Embed In -> View. Just select your UILabel first :)
– Graham Perks
Apr 26 '17 at 18:58
1
1
drawTextInRect works only for 1 line, intrinsicContentSize does not work with horizontal padding. Wrap UILabel inside UIView is the good way to go– onmyway133
Jun 3 '15 at 8:31
drawTextInRect works only for 1 line, intrinsicContentSize does not work with horizontal padding. Wrap UILabel inside UIView is the good way to go– onmyway133
Jun 3 '15 at 8:31
4
4
If you're in IB, now is the time to remember the menu Editor -> Embed In -> View. Just select your UILabel first :)
– Graham Perks
Apr 26 '17 at 18:58
If you're in IB, now is the time to remember the menu Editor -> Embed In -> View. Just select your UILabel first :)
– Graham Perks
Apr 26 '17 at 18:58
add a comment |
up vote
16
down vote
Just use a UIButton, its already built in. Turn off all the extra button features and you have a label that you can set edge instets on.
let button = UIButton()
button.contentEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
button.setTitle("title", for: .normal)
button.tintColor = .white // this will be the textColor
button.isUserInteractionEnabled = false
1
Hey this is a great tip! No extensions required! :-D
– Felipe Ferri
Aug 16 '17 at 14:35
1
SettingisUserInteractionEnabled = falseis handy to disable it.
– mxcl
Sep 11 '17 at 5:56
Great tip... I'd rather do this than going for an extension.
– Ross
Jan 14 at 15:21
Nice tip, with the big advantage that it can also be done in the Interface Builder
– Ely
Sep 13 at 8:42
The best solution without subclassing and etc.
– MeGaPk
Nov 19 at 12:42
add a comment |
up vote
16
down vote
Just use a UIButton, its already built in. Turn off all the extra button features and you have a label that you can set edge instets on.
let button = UIButton()
button.contentEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
button.setTitle("title", for: .normal)
button.tintColor = .white // this will be the textColor
button.isUserInteractionEnabled = false
1
Hey this is a great tip! No extensions required! :-D
– Felipe Ferri
Aug 16 '17 at 14:35
1
SettingisUserInteractionEnabled = falseis handy to disable it.
– mxcl
Sep 11 '17 at 5:56
Great tip... I'd rather do this than going for an extension.
– Ross
Jan 14 at 15:21
Nice tip, with the big advantage that it can also be done in the Interface Builder
– Ely
Sep 13 at 8:42
The best solution without subclassing and etc.
– MeGaPk
Nov 19 at 12:42
add a comment |
up vote
16
down vote
up vote
16
down vote
Just use a UIButton, its already built in. Turn off all the extra button features and you have a label that you can set edge instets on.
let button = UIButton()
button.contentEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
button.setTitle("title", for: .normal)
button.tintColor = .white // this will be the textColor
button.isUserInteractionEnabled = false
Just use a UIButton, its already built in. Turn off all the extra button features and you have a label that you can set edge instets on.
let button = UIButton()
button.contentEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
button.setTitle("title", for: .normal)
button.tintColor = .white // this will be the textColor
button.isUserInteractionEnabled = false
edited Sep 11 '17 at 6:06
mxcl
19.1k117790
19.1k117790
answered Jul 28 '17 at 12:09
Steve M
66454
66454
1
Hey this is a great tip! No extensions required! :-D
– Felipe Ferri
Aug 16 '17 at 14:35
1
SettingisUserInteractionEnabled = falseis handy to disable it.
– mxcl
Sep 11 '17 at 5:56
Great tip... I'd rather do this than going for an extension.
– Ross
Jan 14 at 15:21
Nice tip, with the big advantage that it can also be done in the Interface Builder
– Ely
Sep 13 at 8:42
The best solution without subclassing and etc.
– MeGaPk
Nov 19 at 12:42
add a comment |
1
Hey this is a great tip! No extensions required! :-D
– Felipe Ferri
Aug 16 '17 at 14:35
1
SettingisUserInteractionEnabled = falseis handy to disable it.
– mxcl
Sep 11 '17 at 5:56
Great tip... I'd rather do this than going for an extension.
– Ross
Jan 14 at 15:21
Nice tip, with the big advantage that it can also be done in the Interface Builder
– Ely
Sep 13 at 8:42
The best solution without subclassing and etc.
– MeGaPk
Nov 19 at 12:42
1
1
Hey this is a great tip! No extensions required! :-D
– Felipe Ferri
Aug 16 '17 at 14:35
Hey this is a great tip! No extensions required! :-D
– Felipe Ferri
Aug 16 '17 at 14:35
1
1
Setting
isUserInteractionEnabled = false is handy to disable it.– mxcl
Sep 11 '17 at 5:56
Setting
isUserInteractionEnabled = false is handy to disable it.– mxcl
Sep 11 '17 at 5:56
Great tip... I'd rather do this than going for an extension.
– Ross
Jan 14 at 15:21
Great tip... I'd rather do this than going for an extension.
– Ross
Jan 14 at 15:21
Nice tip, with the big advantage that it can also be done in the Interface Builder
– Ely
Sep 13 at 8:42
Nice tip, with the big advantage that it can also be done in the Interface Builder
– Ely
Sep 13 at 8:42
The best solution without subclassing and etc.
– MeGaPk
Nov 19 at 12:42
The best solution without subclassing and etc.
– MeGaPk
Nov 19 at 12:42
add a comment |
up vote
9
down vote
Without Storyboard:
class PaddingLabel: UILabel {
var topInset: CGFloat
var bottomInset: CGFloat
var leftInset: CGFloat
var rightInset: CGFloat
required init(withInsets top: CGFloat, _ bottom: CGFloat,_ left: CGFloat,_ right: CGFloat) {
self.topInset = top
self.bottomInset = bottom
self.leftInset = left
self.rightInset = right
super.init(frame: CGRect.zero)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func drawText(in rect: CGRect) {
let insets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}
override var intrinsicContentSize: CGSize {
get {
var contentSize = super.intrinsicContentSize
contentSize.height += topInset + bottomInset
contentSize.width += leftInset + rightInset
return contentSize
}
}
}
Usage:
let label = PaddingLabel(8, 8, 16, 16)
label.font = .boldSystemFont(ofSize: 16)
label.text = "Hello World"
label.backgroundColor = .black
label.textColor = .white
label.textAlignment = .center
label.layer.cornerRadius = 8
label.clipsToBounds = true
label.sizeToFit()
view.addSubview(label)
Result:

Works, but do you know how to make it accept multiple lines? Just change init with "PaddingLabel(withInsets: 8, 8, 16, 16)"
– Camilo Ortegón
Aug 11 '17 at 20:12
add a comment |
up vote
9
down vote
Without Storyboard:
class PaddingLabel: UILabel {
var topInset: CGFloat
var bottomInset: CGFloat
var leftInset: CGFloat
var rightInset: CGFloat
required init(withInsets top: CGFloat, _ bottom: CGFloat,_ left: CGFloat,_ right: CGFloat) {
self.topInset = top
self.bottomInset = bottom
self.leftInset = left
self.rightInset = right
super.init(frame: CGRect.zero)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func drawText(in rect: CGRect) {
let insets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}
override var intrinsicContentSize: CGSize {
get {
var contentSize = super.intrinsicContentSize
contentSize.height += topInset + bottomInset
contentSize.width += leftInset + rightInset
return contentSize
}
}
}
Usage:
let label = PaddingLabel(8, 8, 16, 16)
label.font = .boldSystemFont(ofSize: 16)
label.text = "Hello World"
label.backgroundColor = .black
label.textColor = .white
label.textAlignment = .center
label.layer.cornerRadius = 8
label.clipsToBounds = true
label.sizeToFit()
view.addSubview(label)
Result:

Works, but do you know how to make it accept multiple lines? Just change init with "PaddingLabel(withInsets: 8, 8, 16, 16)"
– Camilo Ortegón
Aug 11 '17 at 20:12
add a comment |
up vote
9
down vote
up vote
9
down vote
Without Storyboard:
class PaddingLabel: UILabel {
var topInset: CGFloat
var bottomInset: CGFloat
var leftInset: CGFloat
var rightInset: CGFloat
required init(withInsets top: CGFloat, _ bottom: CGFloat,_ left: CGFloat,_ right: CGFloat) {
self.topInset = top
self.bottomInset = bottom
self.leftInset = left
self.rightInset = right
super.init(frame: CGRect.zero)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func drawText(in rect: CGRect) {
let insets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}
override var intrinsicContentSize: CGSize {
get {
var contentSize = super.intrinsicContentSize
contentSize.height += topInset + bottomInset
contentSize.width += leftInset + rightInset
return contentSize
}
}
}
Usage:
let label = PaddingLabel(8, 8, 16, 16)
label.font = .boldSystemFont(ofSize: 16)
label.text = "Hello World"
label.backgroundColor = .black
label.textColor = .white
label.textAlignment = .center
label.layer.cornerRadius = 8
label.clipsToBounds = true
label.sizeToFit()
view.addSubview(label)
Result:

Without Storyboard:
class PaddingLabel: UILabel {
var topInset: CGFloat
var bottomInset: CGFloat
var leftInset: CGFloat
var rightInset: CGFloat
required init(withInsets top: CGFloat, _ bottom: CGFloat,_ left: CGFloat,_ right: CGFloat) {
self.topInset = top
self.bottomInset = bottom
self.leftInset = left
self.rightInset = right
super.init(frame: CGRect.zero)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func drawText(in rect: CGRect) {
let insets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}
override var intrinsicContentSize: CGSize {
get {
var contentSize = super.intrinsicContentSize
contentSize.height += topInset + bottomInset
contentSize.width += leftInset + rightInset
return contentSize
}
}
}
Usage:
let label = PaddingLabel(8, 8, 16, 16)
label.font = .boldSystemFont(ofSize: 16)
label.text = "Hello World"
label.backgroundColor = .black
label.textColor = .white
label.textAlignment = .center
label.layer.cornerRadius = 8
label.clipsToBounds = true
label.sizeToFit()
view.addSubview(label)
Result:

answered Jul 27 '17 at 8:27
Alice Chan
1,511299
1,511299
Works, but do you know how to make it accept multiple lines? Just change init with "PaddingLabel(withInsets: 8, 8, 16, 16)"
– Camilo Ortegón
Aug 11 '17 at 20:12
add a comment |
Works, but do you know how to make it accept multiple lines? Just change init with "PaddingLabel(withInsets: 8, 8, 16, 16)"
– Camilo Ortegón
Aug 11 '17 at 20:12
Works, but do you know how to make it accept multiple lines? Just change init with "PaddingLabel(withInsets: 8, 8, 16, 16)"
– Camilo Ortegón
Aug 11 '17 at 20:12
Works, but do you know how to make it accept multiple lines? Just change init with "PaddingLabel(withInsets: 8, 8, 16, 16)"
– Camilo Ortegón
Aug 11 '17 at 20:12
add a comment |
up vote
6
down vote
Swift 3 Code with Implementation Example
class UIMarginLabel: UILabel {
var topInset: CGFloat = 0
var rightInset: CGFloat = 0
var bottomInset: CGFloat = 0
var leftInset: CGFloat = 0
override func drawText(in rect: CGRect) {
let insets: UIEdgeInsets = UIEdgeInsets(top: self.topInset, left: self.leftInset, bottom: self.bottomInset, right: self.rightInset)
self.setNeedsLayout()
return super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}
}
class LabelVC: UIViewController {
//Outlets
@IBOutlet weak var labelWithMargin: UIMarginLabel!
override func viewDidLoad() {
super.viewDidLoad()
//Label settings.
labelWithMargin.leftInset = 10
view.layoutIfNeeded()
}
}
Don't forget to add class name UIMarginLabel in storyboard label object.
Happy Coding!
add a comment |
up vote
6
down vote
Swift 3 Code with Implementation Example
class UIMarginLabel: UILabel {
var topInset: CGFloat = 0
var rightInset: CGFloat = 0
var bottomInset: CGFloat = 0
var leftInset: CGFloat = 0
override func drawText(in rect: CGRect) {
let insets: UIEdgeInsets = UIEdgeInsets(top: self.topInset, left: self.leftInset, bottom: self.bottomInset, right: self.rightInset)
self.setNeedsLayout()
return super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}
}
class LabelVC: UIViewController {
//Outlets
@IBOutlet weak var labelWithMargin: UIMarginLabel!
override func viewDidLoad() {
super.viewDidLoad()
//Label settings.
labelWithMargin.leftInset = 10
view.layoutIfNeeded()
}
}
Don't forget to add class name UIMarginLabel in storyboard label object.
Happy Coding!
add a comment |
up vote
6
down vote
up vote
6
down vote
Swift 3 Code with Implementation Example
class UIMarginLabel: UILabel {
var topInset: CGFloat = 0
var rightInset: CGFloat = 0
var bottomInset: CGFloat = 0
var leftInset: CGFloat = 0
override func drawText(in rect: CGRect) {
let insets: UIEdgeInsets = UIEdgeInsets(top: self.topInset, left: self.leftInset, bottom: self.bottomInset, right: self.rightInset)
self.setNeedsLayout()
return super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}
}
class LabelVC: UIViewController {
//Outlets
@IBOutlet weak var labelWithMargin: UIMarginLabel!
override func viewDidLoad() {
super.viewDidLoad()
//Label settings.
labelWithMargin.leftInset = 10
view.layoutIfNeeded()
}
}
Don't forget to add class name UIMarginLabel in storyboard label object.
Happy Coding!
Swift 3 Code with Implementation Example
class UIMarginLabel: UILabel {
var topInset: CGFloat = 0
var rightInset: CGFloat = 0
var bottomInset: CGFloat = 0
var leftInset: CGFloat = 0
override func drawText(in rect: CGRect) {
let insets: UIEdgeInsets = UIEdgeInsets(top: self.topInset, left: self.leftInset, bottom: self.bottomInset, right: self.rightInset)
self.setNeedsLayout()
return super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}
}
class LabelVC: UIViewController {
//Outlets
@IBOutlet weak var labelWithMargin: UIMarginLabel!
override func viewDidLoad() {
super.viewDidLoad()
//Label settings.
labelWithMargin.leftInset = 10
view.layoutIfNeeded()
}
}
Don't forget to add class name UIMarginLabel in storyboard label object.
Happy Coding!
answered Jan 28 '17 at 19:42
mriaz0011
1,333156
1,333156
add a comment |
add a comment |
up vote
6
down vote
Swift 3, iOS10 solution:
open class UIInsetLabel: UILabel {
open var insets : UIEdgeInsets = UIEdgeInsets() {
didSet {
super.invalidateIntrinsicContentSize()
}
}
open override var intrinsicContentSize: CGSize {
var size = super.intrinsicContentSize
size.width += insets.left + insets.right
size.height += insets.top + insets.bottom
return size
}
override open func drawText(in rect: CGRect) {
return super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}
}
add a comment |
up vote
6
down vote
Swift 3, iOS10 solution:
open class UIInsetLabel: UILabel {
open var insets : UIEdgeInsets = UIEdgeInsets() {
didSet {
super.invalidateIntrinsicContentSize()
}
}
open override var intrinsicContentSize: CGSize {
var size = super.intrinsicContentSize
size.width += insets.left + insets.right
size.height += insets.top + insets.bottom
return size
}
override open func drawText(in rect: CGRect) {
return super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}
}
add a comment |
up vote
6
down vote
up vote
6
down vote
Swift 3, iOS10 solution:
open class UIInsetLabel: UILabel {
open var insets : UIEdgeInsets = UIEdgeInsets() {
didSet {
super.invalidateIntrinsicContentSize()
}
}
open override var intrinsicContentSize: CGSize {
var size = super.intrinsicContentSize
size.width += insets.left + insets.right
size.height += insets.top + insets.bottom
return size
}
override open func drawText(in rect: CGRect) {
return super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}
}
Swift 3, iOS10 solution:
open class UIInsetLabel: UILabel {
open var insets : UIEdgeInsets = UIEdgeInsets() {
didSet {
super.invalidateIntrinsicContentSize()
}
}
open override var intrinsicContentSize: CGSize {
var size = super.intrinsicContentSize
size.width += insets.left + insets.right
size.height += insets.top + insets.bottom
return size
}
override open func drawText(in rect: CGRect) {
return super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}
}
answered Feb 4 '17 at 21:52
andrewz
1,74532544
1,74532544
add a comment |
add a comment |
up vote
5
down vote
Subclass UILabel. (File-New-File- CocoaTouchClass-make Subclass of UILabel).
// sampleLabel.swift
import UIKit
class sampleLabel: UILabel {
let topInset = CGFloat(5.0), bottomInset = CGFloat(5.0), leftInset = CGFloat(8.0), rightInset = CGFloat(8.0)
override func drawTextInRect(rect: CGRect) {
let insets: UIEdgeInsets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawTextInRect(UIEdgeInsetsInsetRect(rect, insets))
}
override func intrinsicContentSize() -> CGSize {
var intrinsicSuperViewContentSize = super.intrinsicContentSize()
intrinsicSuperViewContentSize.height += topInset + bottomInset
intrinsicSuperViewContentSize.width += leftInset + rightInset
return intrinsicSuperViewContentSize
}
}
On ViewController:
override func viewDidLoad() {
super.viewDidLoad()
let labelName = sampleLabel(frame: CGRectMake(0, 100, 300, 25))
labelName.text = "Sample Label"
labelName.backgroundColor = UIColor.grayColor()
labelName.textColor = UIColor.redColor()
labelName.shadowColor = UIColor.blackColor()
labelName.font = UIFont(name: "HelveticaNeue", size: CGFloat(22))
self.view.addSubview(labelName)
}
OR Associate custom UILabel class on Storyboard as Label's class.
i would up vote if you change those hardcoded values into class properties, i am already using this code.
– Juan Boero
Apr 8 '16 at 21:43
@ Juan : drawTextInRect is a default class property of UILabel which we are unable to override using code. The best practice to subclass UILabel and add required frame change. Anyhow, it is convenient as Inheritance feature.
– A.G
Apr 11 '16 at 6:16
this is correct, however as of Swift 3 at least, intrinsicContentSize is not a function but rather a property, so should be "override var intrinsicContentSize: CGFloat {}" instead of "override func intrinsicContentSize", just a note.
– joey
Jun 9 '17 at 7:05
add a comment |
up vote
5
down vote
Subclass UILabel. (File-New-File- CocoaTouchClass-make Subclass of UILabel).
// sampleLabel.swift
import UIKit
class sampleLabel: UILabel {
let topInset = CGFloat(5.0), bottomInset = CGFloat(5.0), leftInset = CGFloat(8.0), rightInset = CGFloat(8.0)
override func drawTextInRect(rect: CGRect) {
let insets: UIEdgeInsets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawTextInRect(UIEdgeInsetsInsetRect(rect, insets))
}
override func intrinsicContentSize() -> CGSize {
var intrinsicSuperViewContentSize = super.intrinsicContentSize()
intrinsicSuperViewContentSize.height += topInset + bottomInset
intrinsicSuperViewContentSize.width += leftInset + rightInset
return intrinsicSuperViewContentSize
}
}
On ViewController:
override func viewDidLoad() {
super.viewDidLoad()
let labelName = sampleLabel(frame: CGRectMake(0, 100, 300, 25))
labelName.text = "Sample Label"
labelName.backgroundColor = UIColor.grayColor()
labelName.textColor = UIColor.redColor()
labelName.shadowColor = UIColor.blackColor()
labelName.font = UIFont(name: "HelveticaNeue", size: CGFloat(22))
self.view.addSubview(labelName)
}
OR Associate custom UILabel class on Storyboard as Label's class.
i would up vote if you change those hardcoded values into class properties, i am already using this code.
– Juan Boero
Apr 8 '16 at 21:43
@ Juan : drawTextInRect is a default class property of UILabel which we are unable to override using code. The best practice to subclass UILabel and add required frame change. Anyhow, it is convenient as Inheritance feature.
– A.G
Apr 11 '16 at 6:16
this is correct, however as of Swift 3 at least, intrinsicContentSize is not a function but rather a property, so should be "override var intrinsicContentSize: CGFloat {}" instead of "override func intrinsicContentSize", just a note.
– joey
Jun 9 '17 at 7:05
add a comment |
up vote
5
down vote
up vote
5
down vote
Subclass UILabel. (File-New-File- CocoaTouchClass-make Subclass of UILabel).
// sampleLabel.swift
import UIKit
class sampleLabel: UILabel {
let topInset = CGFloat(5.0), bottomInset = CGFloat(5.0), leftInset = CGFloat(8.0), rightInset = CGFloat(8.0)
override func drawTextInRect(rect: CGRect) {
let insets: UIEdgeInsets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawTextInRect(UIEdgeInsetsInsetRect(rect, insets))
}
override func intrinsicContentSize() -> CGSize {
var intrinsicSuperViewContentSize = super.intrinsicContentSize()
intrinsicSuperViewContentSize.height += topInset + bottomInset
intrinsicSuperViewContentSize.width += leftInset + rightInset
return intrinsicSuperViewContentSize
}
}
On ViewController:
override func viewDidLoad() {
super.viewDidLoad()
let labelName = sampleLabel(frame: CGRectMake(0, 100, 300, 25))
labelName.text = "Sample Label"
labelName.backgroundColor = UIColor.grayColor()
labelName.textColor = UIColor.redColor()
labelName.shadowColor = UIColor.blackColor()
labelName.font = UIFont(name: "HelveticaNeue", size: CGFloat(22))
self.view.addSubview(labelName)
}
OR Associate custom UILabel class on Storyboard as Label's class.
Subclass UILabel. (File-New-File- CocoaTouchClass-make Subclass of UILabel).
// sampleLabel.swift
import UIKit
class sampleLabel: UILabel {
let topInset = CGFloat(5.0), bottomInset = CGFloat(5.0), leftInset = CGFloat(8.0), rightInset = CGFloat(8.0)
override func drawTextInRect(rect: CGRect) {
let insets: UIEdgeInsets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawTextInRect(UIEdgeInsetsInsetRect(rect, insets))
}
override func intrinsicContentSize() -> CGSize {
var intrinsicSuperViewContentSize = super.intrinsicContentSize()
intrinsicSuperViewContentSize.height += topInset + bottomInset
intrinsicSuperViewContentSize.width += leftInset + rightInset
return intrinsicSuperViewContentSize
}
}
On ViewController:
override func viewDidLoad() {
super.viewDidLoad()
let labelName = sampleLabel(frame: CGRectMake(0, 100, 300, 25))
labelName.text = "Sample Label"
labelName.backgroundColor = UIColor.grayColor()
labelName.textColor = UIColor.redColor()
labelName.shadowColor = UIColor.blackColor()
labelName.font = UIFont(name: "HelveticaNeue", size: CGFloat(22))
self.view.addSubview(labelName)
}
OR Associate custom UILabel class on Storyboard as Label's class.
answered Mar 8 '16 at 7:03
A.G
10.2k7148
10.2k7148
i would up vote if you change those hardcoded values into class properties, i am already using this code.
– Juan Boero
Apr 8 '16 at 21:43
@ Juan : drawTextInRect is a default class property of UILabel which we are unable to override using code. The best practice to subclass UILabel and add required frame change. Anyhow, it is convenient as Inheritance feature.
– A.G
Apr 11 '16 at 6:16
this is correct, however as of Swift 3 at least, intrinsicContentSize is not a function but rather a property, so should be "override var intrinsicContentSize: CGFloat {}" instead of "override func intrinsicContentSize", just a note.
– joey
Jun 9 '17 at 7:05
add a comment |
i would up vote if you change those hardcoded values into class properties, i am already using this code.
– Juan Boero
Apr 8 '16 at 21:43
@ Juan : drawTextInRect is a default class property of UILabel which we are unable to override using code. The best practice to subclass UILabel and add required frame change. Anyhow, it is convenient as Inheritance feature.
– A.G
Apr 11 '16 at 6:16
this is correct, however as of Swift 3 at least, intrinsicContentSize is not a function but rather a property, so should be "override var intrinsicContentSize: CGFloat {}" instead of "override func intrinsicContentSize", just a note.
– joey
Jun 9 '17 at 7:05
i would up vote if you change those hardcoded values into class properties, i am already using this code.
– Juan Boero
Apr 8 '16 at 21:43
i would up vote if you change those hardcoded values into class properties, i am already using this code.
– Juan Boero
Apr 8 '16 at 21:43
@ Juan : drawTextInRect is a default class property of UILabel which we are unable to override using code. The best practice to subclass UILabel and add required frame change. Anyhow, it is convenient as Inheritance feature.
– A.G
Apr 11 '16 at 6:16
@ Juan : drawTextInRect is a default class property of UILabel which we are unable to override using code. The best practice to subclass UILabel and add required frame change. Anyhow, it is convenient as Inheritance feature.
– A.G
Apr 11 '16 at 6:16
this is correct, however as of Swift 3 at least, intrinsicContentSize is not a function but rather a property, so should be "override var intrinsicContentSize: CGFloat {}" instead of "override func intrinsicContentSize", just a note.
– joey
Jun 9 '17 at 7:05
this is correct, however as of Swift 3 at least, intrinsicContentSize is not a function but rather a property, so should be "override var intrinsicContentSize: CGFloat {}" instead of "override func intrinsicContentSize", just a note.
– joey
Jun 9 '17 at 7:05
add a comment |
up vote
4
down vote
I edited a little in the accepted answer. There is a problem when leftInset and rightInset increase, a part of text will be disappeared, b/c the width of label will be narrowed but the height does not increase as figure:

To resolve this problem you need to re-calculate height of text as follow:
@IBDesignable class PaddingLabel: UILabel {
@IBInspectable var topInset: CGFloat = 20.0
@IBInspectable var bottomInset: CGFloat = 20.0
@IBInspectable var leftInset: CGFloat = 20.0
@IBInspectable var rightInset: CGFloat = 20.0
override func drawTextInRect(rect: CGRect) {
let insets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawTextInRect(UIEdgeInsetsInsetRect(rect, insets))
}
override func intrinsicContentSize() -> CGSize {
var intrinsicSuperViewContentSize = super.intrinsicContentSize()
let textWidth = frame.size.width - (self.leftInset + self.rightInset)
let newSize = self.text!.boundingRectWithSize(CGSizeMake(textWidth, CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: self.font], context: nil)
intrinsicSuperViewContentSize.height = ceil(newSize.size.height) + self.topInset + self.bottomInset
return intrinsicSuperViewContentSize
}
}
and result:

I hope to help some people in the same situation as me.
2
If you plan to use Swift 3.0, you must change function names, as new Apple language completely breaks previous func definition. So,override func drawTextInRect(rect: CGRect)becomesoverride func drawText(in rect: CGRect)andoverride func intrinsicContentSize() -> CGSizebecomesoverride var intrinsicContentSize : CGSizeEnjoy!
– DoK
Sep 30 '16 at 20:06
add a comment |
up vote
4
down vote
I edited a little in the accepted answer. There is a problem when leftInset and rightInset increase, a part of text will be disappeared, b/c the width of label will be narrowed but the height does not increase as figure:

To resolve this problem you need to re-calculate height of text as follow:
@IBDesignable class PaddingLabel: UILabel {
@IBInspectable var topInset: CGFloat = 20.0
@IBInspectable var bottomInset: CGFloat = 20.0
@IBInspectable var leftInset: CGFloat = 20.0
@IBInspectable var rightInset: CGFloat = 20.0
override func drawTextInRect(rect: CGRect) {
let insets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawTextInRect(UIEdgeInsetsInsetRect(rect, insets))
}
override func intrinsicContentSize() -> CGSize {
var intrinsicSuperViewContentSize = super.intrinsicContentSize()
let textWidth = frame.size.width - (self.leftInset + self.rightInset)
let newSize = self.text!.boundingRectWithSize(CGSizeMake(textWidth, CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: self.font], context: nil)
intrinsicSuperViewContentSize.height = ceil(newSize.size.height) + self.topInset + self.bottomInset
return intrinsicSuperViewContentSize
}
}
and result:

I hope to help some people in the same situation as me.
2
If you plan to use Swift 3.0, you must change function names, as new Apple language completely breaks previous func definition. So,override func drawTextInRect(rect: CGRect)becomesoverride func drawText(in rect: CGRect)andoverride func intrinsicContentSize() -> CGSizebecomesoverride var intrinsicContentSize : CGSizeEnjoy!
– DoK
Sep 30 '16 at 20:06
add a comment |
up vote
4
down vote
up vote
4
down vote
I edited a little in the accepted answer. There is a problem when leftInset and rightInset increase, a part of text will be disappeared, b/c the width of label will be narrowed but the height does not increase as figure:

To resolve this problem you need to re-calculate height of text as follow:
@IBDesignable class PaddingLabel: UILabel {
@IBInspectable var topInset: CGFloat = 20.0
@IBInspectable var bottomInset: CGFloat = 20.0
@IBInspectable var leftInset: CGFloat = 20.0
@IBInspectable var rightInset: CGFloat = 20.0
override func drawTextInRect(rect: CGRect) {
let insets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawTextInRect(UIEdgeInsetsInsetRect(rect, insets))
}
override func intrinsicContentSize() -> CGSize {
var intrinsicSuperViewContentSize = super.intrinsicContentSize()
let textWidth = frame.size.width - (self.leftInset + self.rightInset)
let newSize = self.text!.boundingRectWithSize(CGSizeMake(textWidth, CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: self.font], context: nil)
intrinsicSuperViewContentSize.height = ceil(newSize.size.height) + self.topInset + self.bottomInset
return intrinsicSuperViewContentSize
}
}
and result:

I hope to help some people in the same situation as me.
I edited a little in the accepted answer. There is a problem when leftInset and rightInset increase, a part of text will be disappeared, b/c the width of label will be narrowed but the height does not increase as figure:

To resolve this problem you need to re-calculate height of text as follow:
@IBDesignable class PaddingLabel: UILabel {
@IBInspectable var topInset: CGFloat = 20.0
@IBInspectable var bottomInset: CGFloat = 20.0
@IBInspectable var leftInset: CGFloat = 20.0
@IBInspectable var rightInset: CGFloat = 20.0
override func drawTextInRect(rect: CGRect) {
let insets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawTextInRect(UIEdgeInsetsInsetRect(rect, insets))
}
override func intrinsicContentSize() -> CGSize {
var intrinsicSuperViewContentSize = super.intrinsicContentSize()
let textWidth = frame.size.width - (self.leftInset + self.rightInset)
let newSize = self.text!.boundingRectWithSize(CGSizeMake(textWidth, CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: self.font], context: nil)
intrinsicSuperViewContentSize.height = ceil(newSize.size.height) + self.topInset + self.bottomInset
return intrinsicSuperViewContentSize
}
}
and result:

I hope to help some people in the same situation as me.
edited Aug 22 '16 at 1:38
answered Aug 17 '16 at 10:42
Quang Tran
1,014712
1,014712
2
If you plan to use Swift 3.0, you must change function names, as new Apple language completely breaks previous func definition. So,override func drawTextInRect(rect: CGRect)becomesoverride func drawText(in rect: CGRect)andoverride func intrinsicContentSize() -> CGSizebecomesoverride var intrinsicContentSize : CGSizeEnjoy!
– DoK
Sep 30 '16 at 20:06
add a comment |
2
If you plan to use Swift 3.0, you must change function names, as new Apple language completely breaks previous func definition. So,override func drawTextInRect(rect: CGRect)becomesoverride func drawText(in rect: CGRect)andoverride func intrinsicContentSize() -> CGSizebecomesoverride var intrinsicContentSize : CGSizeEnjoy!
– DoK
Sep 30 '16 at 20:06
2
2
If you plan to use Swift 3.0, you must change function names, as new Apple language completely breaks previous func definition. So,
override func drawTextInRect(rect: CGRect) becomes override func drawText(in rect: CGRect) and override func intrinsicContentSize() -> CGSize becomes override var intrinsicContentSize : CGSize Enjoy!– DoK
Sep 30 '16 at 20:06
If you plan to use Swift 3.0, you must change function names, as new Apple language completely breaks previous func definition. So,
override func drawTextInRect(rect: CGRect) becomes override func drawText(in rect: CGRect) and override func intrinsicContentSize() -> CGSize becomes override var intrinsicContentSize : CGSize Enjoy!– DoK
Sep 30 '16 at 20:06
add a comment |
up vote
4
down vote
As per Swift 4.2 (Xcode 10 beta 6) "UIEdgeInsetsInsetRect" being deprecated.
I've also declared the class public to make it more useful.
public class UIPaddedLabel: UILabel {
@IBInspectable var topInset: CGFloat = 5.0
@IBInspectable var bottomInset: CGFloat = 5.0
@IBInspectable var leftInset: CGFloat = 7.0
@IBInspectable var rightInset: CGFloat = 7.0
public override func drawText(in rect: CGRect) {
let insets = UIEdgeInsets.init(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawText(in: rect.inset(by: insets))
}
public override var intrinsicContentSize: CGSize {
let size = super.intrinsicContentSize
return CGSize(width: size.width + leftInset + rightInset,
height: size.height + topInset + bottomInset)
}
public override func sizeToFit() {
super.sizeThatFits(intrinsicContentSize)
}
}
It works well. But I try to use it inside a CollectionViewCell and it doesn't resize well after reuse (event after sizeToFit and layoutIfNeeded). Any id how to resize it?
– Bogy
Sep 19 at 8:25
1
I did update sizeToFit() to make it work with reusable view
– Bogy
Sep 20 at 12:44
sizeToFit()should be public as: "Overriding instance method must be as accessible as its enclosing type"
– psyFi
Oct 23 at 18:57
add a comment |
up vote
4
down vote
As per Swift 4.2 (Xcode 10 beta 6) "UIEdgeInsetsInsetRect" being deprecated.
I've also declared the class public to make it more useful.
public class UIPaddedLabel: UILabel {
@IBInspectable var topInset: CGFloat = 5.0
@IBInspectable var bottomInset: CGFloat = 5.0
@IBInspectable var leftInset: CGFloat = 7.0
@IBInspectable var rightInset: CGFloat = 7.0
public override func drawText(in rect: CGRect) {
let insets = UIEdgeInsets.init(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawText(in: rect.inset(by: insets))
}
public override var intrinsicContentSize: CGSize {
let size = super.intrinsicContentSize
return CGSize(width: size.width + leftInset + rightInset,
height: size.height + topInset + bottomInset)
}
public override func sizeToFit() {
super.sizeThatFits(intrinsicContentSize)
}
}
It works well. But I try to use it inside a CollectionViewCell and it doesn't resize well after reuse (event after sizeToFit and layoutIfNeeded). Any id how to resize it?
– Bogy
Sep 19 at 8:25
1
I did update sizeToFit() to make it work with reusable view
– Bogy
Sep 20 at 12:44
sizeToFit()should be public as: "Overriding instance method must be as accessible as its enclosing type"
– psyFi
Oct 23 at 18:57
add a comment |
up vote
4
down vote
up vote
4
down vote
As per Swift 4.2 (Xcode 10 beta 6) "UIEdgeInsetsInsetRect" being deprecated.
I've also declared the class public to make it more useful.
public class UIPaddedLabel: UILabel {
@IBInspectable var topInset: CGFloat = 5.0
@IBInspectable var bottomInset: CGFloat = 5.0
@IBInspectable var leftInset: CGFloat = 7.0
@IBInspectable var rightInset: CGFloat = 7.0
public override func drawText(in rect: CGRect) {
let insets = UIEdgeInsets.init(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawText(in: rect.inset(by: insets))
}
public override var intrinsicContentSize: CGSize {
let size = super.intrinsicContentSize
return CGSize(width: size.width + leftInset + rightInset,
height: size.height + topInset + bottomInset)
}
public override func sizeToFit() {
super.sizeThatFits(intrinsicContentSize)
}
}
As per Swift 4.2 (Xcode 10 beta 6) "UIEdgeInsetsInsetRect" being deprecated.
I've also declared the class public to make it more useful.
public class UIPaddedLabel: UILabel {
@IBInspectable var topInset: CGFloat = 5.0
@IBInspectable var bottomInset: CGFloat = 5.0
@IBInspectable var leftInset: CGFloat = 7.0
@IBInspectable var rightInset: CGFloat = 7.0
public override func drawText(in rect: CGRect) {
let insets = UIEdgeInsets.init(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawText(in: rect.inset(by: insets))
}
public override var intrinsicContentSize: CGSize {
let size = super.intrinsicContentSize
return CGSize(width: size.width + leftInset + rightInset,
height: size.height + topInset + bottomInset)
}
public override func sizeToFit() {
super.sizeThatFits(intrinsicContentSize)
}
}
edited Oct 23 at 23:41
psyFi
138110
138110
answered Aug 19 at 13:25
Stéphane de Luca
3,19232851
3,19232851
It works well. But I try to use it inside a CollectionViewCell and it doesn't resize well after reuse (event after sizeToFit and layoutIfNeeded). Any id how to resize it?
– Bogy
Sep 19 at 8:25
1
I did update sizeToFit() to make it work with reusable view
– Bogy
Sep 20 at 12:44
sizeToFit()should be public as: "Overriding instance method must be as accessible as its enclosing type"
– psyFi
Oct 23 at 18:57
add a comment |
It works well. But I try to use it inside a CollectionViewCell and it doesn't resize well after reuse (event after sizeToFit and layoutIfNeeded). Any id how to resize it?
– Bogy
Sep 19 at 8:25
1
I did update sizeToFit() to make it work with reusable view
– Bogy
Sep 20 at 12:44
sizeToFit()should be public as: "Overriding instance method must be as accessible as its enclosing type"
– psyFi
Oct 23 at 18:57
It works well. But I try to use it inside a CollectionViewCell and it doesn't resize well after reuse (event after sizeToFit and layoutIfNeeded). Any id how to resize it?
– Bogy
Sep 19 at 8:25
It works well. But I try to use it inside a CollectionViewCell and it doesn't resize well after reuse (event after sizeToFit and layoutIfNeeded). Any id how to resize it?
– Bogy
Sep 19 at 8:25
1
1
I did update sizeToFit() to make it work with reusable view
– Bogy
Sep 20 at 12:44
I did update sizeToFit() to make it work with reusable view
– Bogy
Sep 20 at 12:44
sizeToFit() should be public as: "Overriding instance method must be as accessible as its enclosing type"– psyFi
Oct 23 at 18:57
sizeToFit() should be public as: "Overriding instance method must be as accessible as its enclosing type"– psyFi
Oct 23 at 18:57
add a comment |
up vote
3
down vote
In Swift 3
best and simple way
class UILabelPadded: UILabel {
override func drawText(in rect: CGRect) {
let insets = UIEdgeInsets.init(top: 0, left: 5, bottom: 0, right: 5)
super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}
}
add a comment |
up vote
3
down vote
In Swift 3
best and simple way
class UILabelPadded: UILabel {
override func drawText(in rect: CGRect) {
let insets = UIEdgeInsets.init(top: 0, left: 5, bottom: 0, right: 5)
super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}
}
add a comment |
up vote
3
down vote
up vote
3
down vote
In Swift 3
best and simple way
class UILabelPadded: UILabel {
override func drawText(in rect: CGRect) {
let insets = UIEdgeInsets.init(top: 0, left: 5, bottom: 0, right: 5)
super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}
}
In Swift 3
best and simple way
class UILabelPadded: UILabel {
override func drawText(in rect: CGRect) {
let insets = UIEdgeInsets.init(top: 0, left: 5, bottom: 0, right: 5)
super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}
}
answered May 29 '17 at 10:05
SanRam
41167
41167
add a comment |
add a comment |
up vote
2
down vote
Easy padding (Swift 3.0, Alvin George answer):
class NewLabel: UILabel {
override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
return self.bounds.insetBy(dx: CGFloat(15.0), dy: CGFloat(15.0))
}
override func draw(_ rect: CGRect) {
super.drawText(in: self.bounds.insetBy(dx: CGFloat(5.0), dy: CGFloat(5.0)))
}
}
add a comment |
up vote
2
down vote
Easy padding (Swift 3.0, Alvin George answer):
class NewLabel: UILabel {
override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
return self.bounds.insetBy(dx: CGFloat(15.0), dy: CGFloat(15.0))
}
override func draw(_ rect: CGRect) {
super.drawText(in: self.bounds.insetBy(dx: CGFloat(5.0), dy: CGFloat(5.0)))
}
}
add a comment |
up vote
2
down vote
up vote
2
down vote
Easy padding (Swift 3.0, Alvin George answer):
class NewLabel: UILabel {
override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
return self.bounds.insetBy(dx: CGFloat(15.0), dy: CGFloat(15.0))
}
override func draw(_ rect: CGRect) {
super.drawText(in: self.bounds.insetBy(dx: CGFloat(5.0), dy: CGFloat(5.0)))
}
}
Easy padding (Swift 3.0, Alvin George answer):
class NewLabel: UILabel {
override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
return self.bounds.insetBy(dx: CGFloat(15.0), dy: CGFloat(15.0))
}
override func draw(_ rect: CGRect) {
super.drawText(in: self.bounds.insetBy(dx: CGFloat(5.0), dy: CGFloat(5.0)))
}
}
answered Oct 10 '16 at 9:55
odemolliens
1,91622225
1,91622225
add a comment |
add a comment |
up vote
2
down vote
Another option without subclassing would be to:
- Set label
text
sizeToFit()
then increase label height a little to simulate padding
label.text = "someText"
label.textAlignment = .center
label.sizeToFit()
label.frame = CGRect( x: label.frame.x, y: label.frame.y,width: label.frame.width + 20,height: label.frame.height + 8)
Surprisingly, this was all I needed, just modified a little to this:label.frame = CGRect( x: label.frame.origin.x - 10, y: label.frame.origin.y - 4, width: label.frame.width + 20,height: label.frame.height + 8)the -10 and -4 for centralizing
– Mofe-hendy Ejegi
Feb 10 at 6:01
add a comment |
up vote
2
down vote
Another option without subclassing would be to:
- Set label
text
sizeToFit()
then increase label height a little to simulate padding
label.text = "someText"
label.textAlignment = .center
label.sizeToFit()
label.frame = CGRect( x: label.frame.x, y: label.frame.y,width: label.frame.width + 20,height: label.frame.height + 8)
Surprisingly, this was all I needed, just modified a little to this:label.frame = CGRect( x: label.frame.origin.x - 10, y: label.frame.origin.y - 4, width: label.frame.width + 20,height: label.frame.height + 8)the -10 and -4 for centralizing
– Mofe-hendy Ejegi
Feb 10 at 6:01
add a comment |
up vote
2
down vote
up vote
2
down vote
Another option without subclassing would be to:
- Set label
text
sizeToFit()
then increase label height a little to simulate padding
label.text = "someText"
label.textAlignment = .center
label.sizeToFit()
label.frame = CGRect( x: label.frame.x, y: label.frame.y,width: label.frame.width + 20,height: label.frame.height + 8)
Another option without subclassing would be to:
- Set label
text
sizeToFit()
then increase label height a little to simulate padding
label.text = "someText"
label.textAlignment = .center
label.sizeToFit()
label.frame = CGRect( x: label.frame.x, y: label.frame.y,width: label.frame.width + 20,height: label.frame.height + 8)
edited May 18 '17 at 12:08
Joe
5,53342046
5,53342046
answered Apr 23 '17 at 9:35
Guy
50569
50569
Surprisingly, this was all I needed, just modified a little to this:label.frame = CGRect( x: label.frame.origin.x - 10, y: label.frame.origin.y - 4, width: label.frame.width + 20,height: label.frame.height + 8)the -10 and -4 for centralizing
– Mofe-hendy Ejegi
Feb 10 at 6:01
add a comment |
Surprisingly, this was all I needed, just modified a little to this:label.frame = CGRect( x: label.frame.origin.x - 10, y: label.frame.origin.y - 4, width: label.frame.width + 20,height: label.frame.height + 8)the -10 and -4 for centralizing
– Mofe-hendy Ejegi
Feb 10 at 6:01
Surprisingly, this was all I needed, just modified a little to this:
label.frame = CGRect( x: label.frame.origin.x - 10, y: label.frame.origin.y - 4, width: label.frame.width + 20,height: label.frame.height + 8) the -10 and -4 for centralizing– Mofe-hendy Ejegi
Feb 10 at 6:01
Surprisingly, this was all I needed, just modified a little to this:
label.frame = CGRect( x: label.frame.origin.x - 10, y: label.frame.origin.y - 4, width: label.frame.width + 20,height: label.frame.height + 8) the -10 and -4 for centralizing– Mofe-hendy Ejegi
Feb 10 at 6:01
add a comment |
up vote
1
down vote
Easy way
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.view.addSubview(makeLabel("my title",x: 0, y: 100, w: 320, h: 30))
}
func makeLabel(title:String, x:CGFloat, y:CGFloat, w:CGFloat, h:CGFloat)->UILabel{
var myLabel : UILabel = UILabel(frame: CGRectMake(x,y,w,h))
myLabel.textAlignment = NSTextAlignment.Right
// inser last char to right
var titlePlus1char = "(title)1"
myLabel.text = titlePlus1char
var titleSize:Int = count(titlePlus1char)-1
myLabel.textColor = UIColor(red:1.0, green:1.0,blue:1.0,alpha:1.0)
myLabel.backgroundColor = UIColor(red: 214/255, green: 167/255, blue: 0/255,alpha:1.0)
// create myMutable String
var myMutableString = NSMutableAttributedString()
// create myMutable font
myMutableString = NSMutableAttributedString(string: titlePlus1char, attributes: [NSFontAttributeName:UIFont(name: "HelveticaNeue", size: 20)!])
// set margin size
myMutableString.addAttribute(NSFontAttributeName, value: UIFont(name: "HelveticaNeue", size: 10)!, range: NSRange(location: titleSize,length: 1))
// set last char to alpha 0
myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor(red:1.0, green:1.0,blue:1.0,alpha:0), range: NSRange(location: titleSize,length: 1))
myLabel.attributedText = myMutableString
return myLabel
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
add a comment |
up vote
1
down vote
Easy way
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.view.addSubview(makeLabel("my title",x: 0, y: 100, w: 320, h: 30))
}
func makeLabel(title:String, x:CGFloat, y:CGFloat, w:CGFloat, h:CGFloat)->UILabel{
var myLabel : UILabel = UILabel(frame: CGRectMake(x,y,w,h))
myLabel.textAlignment = NSTextAlignment.Right
// inser last char to right
var titlePlus1char = "(title)1"
myLabel.text = titlePlus1char
var titleSize:Int = count(titlePlus1char)-1
myLabel.textColor = UIColor(red:1.0, green:1.0,blue:1.0,alpha:1.0)
myLabel.backgroundColor = UIColor(red: 214/255, green: 167/255, blue: 0/255,alpha:1.0)
// create myMutable String
var myMutableString = NSMutableAttributedString()
// create myMutable font
myMutableString = NSMutableAttributedString(string: titlePlus1char, attributes: [NSFontAttributeName:UIFont(name: "HelveticaNeue", size: 20)!])
// set margin size
myMutableString.addAttribute(NSFontAttributeName, value: UIFont(name: "HelveticaNeue", size: 10)!, range: NSRange(location: titleSize,length: 1))
// set last char to alpha 0
myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor(red:1.0, green:1.0,blue:1.0,alpha:0), range: NSRange(location: titleSize,length: 1))
myLabel.attributedText = myMutableString
return myLabel
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
add a comment |
up vote
1
down vote
up vote
1
down vote
Easy way
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.view.addSubview(makeLabel("my title",x: 0, y: 100, w: 320, h: 30))
}
func makeLabel(title:String, x:CGFloat, y:CGFloat, w:CGFloat, h:CGFloat)->UILabel{
var myLabel : UILabel = UILabel(frame: CGRectMake(x,y,w,h))
myLabel.textAlignment = NSTextAlignment.Right
// inser last char to right
var titlePlus1char = "(title)1"
myLabel.text = titlePlus1char
var titleSize:Int = count(titlePlus1char)-1
myLabel.textColor = UIColor(red:1.0, green:1.0,blue:1.0,alpha:1.0)
myLabel.backgroundColor = UIColor(red: 214/255, green: 167/255, blue: 0/255,alpha:1.0)
// create myMutable String
var myMutableString = NSMutableAttributedString()
// create myMutable font
myMutableString = NSMutableAttributedString(string: titlePlus1char, attributes: [NSFontAttributeName:UIFont(name: "HelveticaNeue", size: 20)!])
// set margin size
myMutableString.addAttribute(NSFontAttributeName, value: UIFont(name: "HelveticaNeue", size: 10)!, range: NSRange(location: titleSize,length: 1))
// set last char to alpha 0
myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor(red:1.0, green:1.0,blue:1.0,alpha:0), range: NSRange(location: titleSize,length: 1))
myLabel.attributedText = myMutableString
return myLabel
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Easy way
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.view.addSubview(makeLabel("my title",x: 0, y: 100, w: 320, h: 30))
}
func makeLabel(title:String, x:CGFloat, y:CGFloat, w:CGFloat, h:CGFloat)->UILabel{
var myLabel : UILabel = UILabel(frame: CGRectMake(x,y,w,h))
myLabel.textAlignment = NSTextAlignment.Right
// inser last char to right
var titlePlus1char = "(title)1"
myLabel.text = titlePlus1char
var titleSize:Int = count(titlePlus1char)-1
myLabel.textColor = UIColor(red:1.0, green:1.0,blue:1.0,alpha:1.0)
myLabel.backgroundColor = UIColor(red: 214/255, green: 167/255, blue: 0/255,alpha:1.0)
// create myMutable String
var myMutableString = NSMutableAttributedString()
// create myMutable font
myMutableString = NSMutableAttributedString(string: titlePlus1char, attributes: [NSFontAttributeName:UIFont(name: "HelveticaNeue", size: 20)!])
// set margin size
myMutableString.addAttribute(NSFontAttributeName, value: UIFont(name: "HelveticaNeue", size: 10)!, range: NSRange(location: titleSize,length: 1))
// set last char to alpha 0
myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor(red:1.0, green:1.0,blue:1.0,alpha:0), range: NSRange(location: titleSize,length: 1))
myLabel.attributedText = myMutableString
return myLabel
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
edited Apr 21 '15 at 3:47
Shashank Agarwal
1,7531419
1,7531419
answered Apr 21 '15 at 3:08
Alex Freitas
112
112
add a comment |
add a comment |
up vote
1
down vote
If you want to add 2px padding around the textRect, just do this:
let insets = UIEdgeInsets(top: -2, left: -2, bottom: -2, right: -2)
label.frame = UIEdgeInsetsInsetRect(textRect, insets)
add a comment |
up vote
1
down vote
If you want to add 2px padding around the textRect, just do this:
let insets = UIEdgeInsets(top: -2, left: -2, bottom: -2, right: -2)
label.frame = UIEdgeInsetsInsetRect(textRect, insets)
add a comment |
up vote
1
down vote
up vote
1
down vote
If you want to add 2px padding around the textRect, just do this:
let insets = UIEdgeInsets(top: -2, left: -2, bottom: -2, right: -2)
label.frame = UIEdgeInsetsInsetRect(textRect, insets)
If you want to add 2px padding around the textRect, just do this:
let insets = UIEdgeInsets(top: -2, left: -2, bottom: -2, right: -2)
label.frame = UIEdgeInsetsInsetRect(textRect, insets)
answered Oct 26 '17 at 4:59
zsong
44.7k21129188
44.7k21129188
add a comment |
add a comment |
up vote
1
down vote
If you don't want or need to use an @IBInspectable / @IBDesignable UILabel in Storyboard (I think those are rendered too slow anyway), then it is cleaner to use UIEdgeInsets instead of 4 different CGFloats.
Code example for Swift 4.2:
class UIPaddedLabel: UILabel {
var padding = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
public override func drawText(in rect: CGRect) {
super.drawText(in: rect.inset(by: padding))
}
public override var intrinsicContentSize: CGSize {
let size = super.intrinsicContentSize
return CGSize(width: size.width + padding.left + padding.right,
height: size.height + padding.top + padding.bottom)
}
}
add a comment |
up vote
1
down vote
If you don't want or need to use an @IBInspectable / @IBDesignable UILabel in Storyboard (I think those are rendered too slow anyway), then it is cleaner to use UIEdgeInsets instead of 4 different CGFloats.
Code example for Swift 4.2:
class UIPaddedLabel: UILabel {
var padding = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
public override func drawText(in rect: CGRect) {
super.drawText(in: rect.inset(by: padding))
}
public override var intrinsicContentSize: CGSize {
let size = super.intrinsicContentSize
return CGSize(width: size.width + padding.left + padding.right,
height: size.height + padding.top + padding.bottom)
}
}
add a comment |
up vote
1
down vote
up vote
1
down vote
If you don't want or need to use an @IBInspectable / @IBDesignable UILabel in Storyboard (I think those are rendered too slow anyway), then it is cleaner to use UIEdgeInsets instead of 4 different CGFloats.
Code example for Swift 4.2:
class UIPaddedLabel: UILabel {
var padding = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
public override func drawText(in rect: CGRect) {
super.drawText(in: rect.inset(by: padding))
}
public override var intrinsicContentSize: CGSize {
let size = super.intrinsicContentSize
return CGSize(width: size.width + padding.left + padding.right,
height: size.height + padding.top + padding.bottom)
}
}
If you don't want or need to use an @IBInspectable / @IBDesignable UILabel in Storyboard (I think those are rendered too slow anyway), then it is cleaner to use UIEdgeInsets instead of 4 different CGFloats.
Code example for Swift 4.2:
class UIPaddedLabel: UILabel {
var padding = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
public override func drawText(in rect: CGRect) {
super.drawText(in: rect.inset(by: padding))
}
public override var intrinsicContentSize: CGSize {
let size = super.intrinsicContentSize
return CGSize(width: size.width + padding.left + padding.right,
height: size.height + padding.top + padding.bottom)
}
}
answered Sep 18 at 14:27
Simon Backx
646713
646713
add a comment |
add a comment |
up vote
1
down vote
Use this code if you are facing text trimming problem while applying padding.
@IBDesignable class PaddingLabel: UILabel {
@IBInspectable var topInset: CGFloat = 5.0
@IBInspectable var bottomInset: CGFloat = 5.0
@IBInspectable var leftInset: CGFloat = 5.0
@IBInspectable var rightInset: CGFloat = 5.0
override func drawText(in rect: CGRect) {
let insets = UIEdgeInsets.init(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}
override var intrinsicContentSize: CGSize {
var intrinsicSuperViewContentSize = super.intrinsicContentSize
let textWidth = frame.size.width - (self.leftInset + self.rightInset)
let newSize = self.text!.boundingRect(with: CGSize(textWidth, CGFloat.greatestFiniteMagnitude), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName: self.font], context: nil)
intrinsicSuperViewContentSize.height = ceil(newSize.size.height) + self.topInset + self.bottomInset
return intrinsicSuperViewContentSize
}
}
extension CGSize{
init(_ width:CGFloat,_ height:CGFloat) {
self.init(width:width,height:height)
}
}
Thank you for posting, I am looking for a solution regardin padding + trimming. It seems to me your solution breaks label.numberOfLines = 0 which I need. Any workaround?
– Don
Oct 5 at 8:38
add a comment |
up vote
1
down vote
Use this code if you are facing text trimming problem while applying padding.
@IBDesignable class PaddingLabel: UILabel {
@IBInspectable var topInset: CGFloat = 5.0
@IBInspectable var bottomInset: CGFloat = 5.0
@IBInspectable var leftInset: CGFloat = 5.0
@IBInspectable var rightInset: CGFloat = 5.0
override func drawText(in rect: CGRect) {
let insets = UIEdgeInsets.init(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}
override var intrinsicContentSize: CGSize {
var intrinsicSuperViewContentSize = super.intrinsicContentSize
let textWidth = frame.size.width - (self.leftInset + self.rightInset)
let newSize = self.text!.boundingRect(with: CGSize(textWidth, CGFloat.greatestFiniteMagnitude), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName: self.font], context: nil)
intrinsicSuperViewContentSize.height = ceil(newSize.size.height) + self.topInset + self.bottomInset
return intrinsicSuperViewContentSize
}
}
extension CGSize{
init(_ width:CGFloat,_ height:CGFloat) {
self.init(width:width,height:height)
}
}
Thank you for posting, I am looking for a solution regardin padding + trimming. It seems to me your solution breaks label.numberOfLines = 0 which I need. Any workaround?
– Don
Oct 5 at 8:38
add a comment |
up vote
1
down vote
up vote
1
down vote
Use this code if you are facing text trimming problem while applying padding.
@IBDesignable class PaddingLabel: UILabel {
@IBInspectable var topInset: CGFloat = 5.0
@IBInspectable var bottomInset: CGFloat = 5.0
@IBInspectable var leftInset: CGFloat = 5.0
@IBInspectable var rightInset: CGFloat = 5.0
override func drawText(in rect: CGRect) {
let insets = UIEdgeInsets.init(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}
override var intrinsicContentSize: CGSize {
var intrinsicSuperViewContentSize = super.intrinsicContentSize
let textWidth = frame.size.width - (self.leftInset + self.rightInset)
let newSize = self.text!.boundingRect(with: CGSize(textWidth, CGFloat.greatestFiniteMagnitude), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName: self.font], context: nil)
intrinsicSuperViewContentSize.height = ceil(newSize.size.height) + self.topInset + self.bottomInset
return intrinsicSuperViewContentSize
}
}
extension CGSize{
init(_ width:CGFloat,_ height:CGFloat) {
self.init(width:width,height:height)
}
}
Use this code if you are facing text trimming problem while applying padding.
@IBDesignable class PaddingLabel: UILabel {
@IBInspectable var topInset: CGFloat = 5.0
@IBInspectable var bottomInset: CGFloat = 5.0
@IBInspectable var leftInset: CGFloat = 5.0
@IBInspectable var rightInset: CGFloat = 5.0
override func drawText(in rect: CGRect) {
let insets = UIEdgeInsets.init(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}
override var intrinsicContentSize: CGSize {
var intrinsicSuperViewContentSize = super.intrinsicContentSize
let textWidth = frame.size.width - (self.leftInset + self.rightInset)
let newSize = self.text!.boundingRect(with: CGSize(textWidth, CGFloat.greatestFiniteMagnitude), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName: self.font], context: nil)
intrinsicSuperViewContentSize.height = ceil(newSize.size.height) + self.topInset + self.bottomInset
return intrinsicSuperViewContentSize
}
}
extension CGSize{
init(_ width:CGFloat,_ height:CGFloat) {
self.init(width:width,height:height)
}
}
edited Oct 23 at 21:07
psyFi
138110
138110
answered Sep 14 at 11:25
ceekay
615
615
Thank you for posting, I am looking for a solution regardin padding + trimming. It seems to me your solution breaks label.numberOfLines = 0 which I need. Any workaround?
– Don
Oct 5 at 8:38
add a comment |
Thank you for posting, I am looking for a solution regardin padding + trimming. It seems to me your solution breaks label.numberOfLines = 0 which I need. Any workaround?
– Don
Oct 5 at 8:38
Thank you for posting, I am looking for a solution regardin padding + trimming. It seems to me your solution breaks label.numberOfLines = 0 which I need. Any workaround?
– Don
Oct 5 at 8:38
Thank you for posting, I am looking for a solution regardin padding + trimming. It seems to me your solution breaks label.numberOfLines = 0 which I need. Any workaround?
– Don
Oct 5 at 8:38
add a comment |
up vote
0
down vote
Easy padding:
import UIKit
class NewLabel: UILabel {
override func textRectForBounds(bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
return CGRectInset(self.bounds, CGFloat(15.0), CGFloat(15.0))
}
override func drawRect(rect: CGRect) {
super.drawTextInRect(CGRectInset(self.bounds,CGFloat(5.0), CGFloat(5.0)))
}
}
3.0 version on bottom page
– odemolliens
Oct 10 '16 at 11:59
add a comment |
up vote
0
down vote
Easy padding:
import UIKit
class NewLabel: UILabel {
override func textRectForBounds(bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
return CGRectInset(self.bounds, CGFloat(15.0), CGFloat(15.0))
}
override func drawRect(rect: CGRect) {
super.drawTextInRect(CGRectInset(self.bounds,CGFloat(5.0), CGFloat(5.0)))
}
}
3.0 version on bottom page
– odemolliens
Oct 10 '16 at 11:59
add a comment |
up vote
0
down vote
up vote
0
down vote
Easy padding:
import UIKit
class NewLabel: UILabel {
override func textRectForBounds(bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
return CGRectInset(self.bounds, CGFloat(15.0), CGFloat(15.0))
}
override func drawRect(rect: CGRect) {
super.drawTextInRect(CGRectInset(self.bounds,CGFloat(5.0), CGFloat(5.0)))
}
}
Easy padding:
import UIKit
class NewLabel: UILabel {
override func textRectForBounds(bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
return CGRectInset(self.bounds, CGFloat(15.0), CGFloat(15.0))
}
override func drawRect(rect: CGRect) {
super.drawTextInRect(CGRectInset(self.bounds,CGFloat(5.0), CGFloat(5.0)))
}
}
answered Apr 11 '16 at 6:17
A.G
10.2k7148
10.2k7148
3.0 version on bottom page
– odemolliens
Oct 10 '16 at 11:59
add a comment |
3.0 version on bottom page
– odemolliens
Oct 10 '16 at 11:59
3.0 version on bottom page
– odemolliens
Oct 10 '16 at 11:59
3.0 version on bottom page
– odemolliens
Oct 10 '16 at 11:59
add a comment |
up vote
0
down vote
Just use autolayout:
let paddedWidth = myLabel.intrinsicContentSize.width + 2 * padding
myLabel.widthAnchor.constraint(equalToConstant: paddedWidth).isActive = true
Done.
add a comment |
up vote
0
down vote
Just use autolayout:
let paddedWidth = myLabel.intrinsicContentSize.width + 2 * padding
myLabel.widthAnchor.constraint(equalToConstant: paddedWidth).isActive = true
Done.
add a comment |
up vote
0
down vote
up vote
0
down vote
Just use autolayout:
let paddedWidth = myLabel.intrinsicContentSize.width + 2 * padding
myLabel.widthAnchor.constraint(equalToConstant: paddedWidth).isActive = true
Done.
Just use autolayout:
let paddedWidth = myLabel.intrinsicContentSize.width + 2 * padding
myLabel.widthAnchor.constraint(equalToConstant: paddedWidth).isActive = true
Done.
answered Mar 7 '17 at 22:17
Tim Shadel
1,20011214
1,20011214
add a comment |
add a comment |
up vote
0
down vote
Similar to other answers, but with a func class to setup the padding dinamically:
class UILabelExtendedView: UILabel
{
var topInset: CGFloat = 4.0
var bottomInset: CGFloat = 4.0
var leftInset: CGFloat = 8.0
var rightInset: CGFloat = 8.0
override func drawText(in rect: CGRect)
{
let insets: UIEdgeInsets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}
override public var intrinsicContentSize: CGSize
{
var contentSize = super.intrinsicContentSize
contentSize.height += topInset + bottomInset
contentSize.width += leftInset + rightInset
return contentSize
}
func setPadding(top: CGFloat, left: CGFloat, bottom: CGFloat, right: CGFloat){
self.topInset = top
self.bottomInset = bottom
self.leftInset = left
self.rightInset = right
let insets: UIEdgeInsets = UIEdgeInsets(top: top, left: left, bottom: bottom, right: right)
super.drawText(in: UIEdgeInsetsInsetRect(self.frame, insets))
}
}
add a comment |
up vote
0
down vote
Similar to other answers, but with a func class to setup the padding dinamically:
class UILabelExtendedView: UILabel
{
var topInset: CGFloat = 4.0
var bottomInset: CGFloat = 4.0
var leftInset: CGFloat = 8.0
var rightInset: CGFloat = 8.0
override func drawText(in rect: CGRect)
{
let insets: UIEdgeInsets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}
override public var intrinsicContentSize: CGSize
{
var contentSize = super.intrinsicContentSize
contentSize.height += topInset + bottomInset
contentSize.width += leftInset + rightInset
return contentSize
}
func setPadding(top: CGFloat, left: CGFloat, bottom: CGFloat, right: CGFloat){
self.topInset = top
self.bottomInset = bottom
self.leftInset = left
self.rightInset = right
let insets: UIEdgeInsets = UIEdgeInsets(top: top, left: left, bottom: bottom, right: right)
super.drawText(in: UIEdgeInsetsInsetRect(self.frame, insets))
}
}
add a comment |
up vote
0
down vote
up vote
0
down vote
Similar to other answers, but with a func class to setup the padding dinamically:
class UILabelExtendedView: UILabel
{
var topInset: CGFloat = 4.0
var bottomInset: CGFloat = 4.0
var leftInset: CGFloat = 8.0
var rightInset: CGFloat = 8.0
override func drawText(in rect: CGRect)
{
let insets: UIEdgeInsets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}
override public var intrinsicContentSize: CGSize
{
var contentSize = super.intrinsicContentSize
contentSize.height += topInset + bottomInset
contentSize.width += leftInset + rightInset
return contentSize
}
func setPadding(top: CGFloat, left: CGFloat, bottom: CGFloat, right: CGFloat){
self.topInset = top
self.bottomInset = bottom
self.leftInset = left
self.rightInset = right
let insets: UIEdgeInsets = UIEdgeInsets(top: top, left: left, bottom: bottom, right: right)
super.drawText(in: UIEdgeInsetsInsetRect(self.frame, insets))
}
}
Similar to other answers, but with a func class to setup the padding dinamically:
class UILabelExtendedView: UILabel
{
var topInset: CGFloat = 4.0
var bottomInset: CGFloat = 4.0
var leftInset: CGFloat = 8.0
var rightInset: CGFloat = 8.0
override func drawText(in rect: CGRect)
{
let insets: UIEdgeInsets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}
override public var intrinsicContentSize: CGSize
{
var contentSize = super.intrinsicContentSize
contentSize.height += topInset + bottomInset
contentSize.width += leftInset + rightInset
return contentSize
}
func setPadding(top: CGFloat, left: CGFloat, bottom: CGFloat, right: CGFloat){
self.topInset = top
self.bottomInset = bottom
self.leftInset = left
self.rightInset = right
let insets: UIEdgeInsets = UIEdgeInsets(top: top, left: left, bottom: bottom, right: right)
super.drawText(in: UIEdgeInsetsInsetRect(self.frame, insets))
}
}
answered Mar 17 '17 at 10:52
Pelanes
2,82712529
2,82712529
add a comment |
add a comment |
up vote
0
down vote
One pragmatic solution is to add blank labels of the same height and color as the main label. Set the leading/trailing space to the main label to zero, align vertical centers, and make the width your desired margin.
add a comment |
up vote
0
down vote
One pragmatic solution is to add blank labels of the same height and color as the main label. Set the leading/trailing space to the main label to zero, align vertical centers, and make the width your desired margin.
add a comment |
up vote
0
down vote
up vote
0
down vote
One pragmatic solution is to add blank labels of the same height and color as the main label. Set the leading/trailing space to the main label to zero, align vertical centers, and make the width your desired margin.
One pragmatic solution is to add blank labels of the same height and color as the main label. Set the leading/trailing space to the main label to zero, align vertical centers, and make the width your desired margin.
answered Apr 21 '17 at 21:44
pks1981
11
11
add a comment |
add a comment |
up vote
0
down vote
An elaboration on Mundi's answer.
i.e. embedding a label in a UIView and enforcing padding through Auto Layout. Example:

Overview:
1) Create a UIView ("panel"), and set its appearance.
2) Create a UILabel and add it to the panel.
3) Add constraints to enforce padding.
4) Add the panel to your view hierarchy, then position the panel.
Details:
1) Create the panel view.
let panel = UIView()
panel.backgroundColor = .green
panel.layer.cornerRadius = 12
2) Create the label, add it to the panel as a subview.
let label = UILabel()
panel.addSubview(label)
3) Add constraints between the edges of the label and the panel. This forces the panel to keep a distance from the label. i.e. "padding"
Editorial: doing all this by hand is super-tedious, verbose and error-prone. I suggest you pick an Auto Layout wrapper from github or write one yourself
label.panel.translatesAutoresizingMaskIntoConstraints = false
label.topAnchor.constraint(equalTo: panel.topAnchor,
constant: vPadding).isActive = true
label.bottomAnchor.constraint(equalTo: panel.bottomAnchor,
constant: -vPadding).isActive = true
label.leadingAnchor.constraint(equalTo: panel.leadingAnchor,
constant: hPadding).isActive = true
label.trailingAnchor.constraint(equalTo: panel.trailingAnchor,
constant: -hPadding).isActive = true
label.textAlignment = .center
4) Add the panel to your view hierarchy and then add positioning constraints. e.g. hug the right-hand side of a tableViewCell, as in the example image.
Note: you only need to add positional constraints, not dimensional constraints: Auto Layout will solve the layout based on both the intrinsicContentSize of the label and the constraints added earlier.
hostView.addSubview(panel)
panel.translatesAutoresizingMaskIntoConstraints = false
panel.trailingAnchor.constraint(equalTo: hostView.trailingAnchor,
constant: -16).isActive = true
panel.centerYAnchor.constraint(equalTo: hostView.centerYAnchor).isActive = true
add a comment |
up vote
0
down vote
An elaboration on Mundi's answer.
i.e. embedding a label in a UIView and enforcing padding through Auto Layout. Example:

Overview:
1) Create a UIView ("panel"), and set its appearance.
2) Create a UILabel and add it to the panel.
3) Add constraints to enforce padding.
4) Add the panel to your view hierarchy, then position the panel.
Details:
1) Create the panel view.
let panel = UIView()
panel.backgroundColor = .green
panel.layer.cornerRadius = 12
2) Create the label, add it to the panel as a subview.
let label = UILabel()
panel.addSubview(label)
3) Add constraints between the edges of the label and the panel. This forces the panel to keep a distance from the label. i.e. "padding"
Editorial: doing all this by hand is super-tedious, verbose and error-prone. I suggest you pick an Auto Layout wrapper from github or write one yourself
label.panel.translatesAutoresizingMaskIntoConstraints = false
label.topAnchor.constraint(equalTo: panel.topAnchor,
constant: vPadding).isActive = true
label.bottomAnchor.constraint(equalTo: panel.bottomAnchor,
constant: -vPadding).isActive = true
label.leadingAnchor.constraint(equalTo: panel.leadingAnchor,
constant: hPadding).isActive = true
label.trailingAnchor.constraint(equalTo: panel.trailingAnchor,
constant: -hPadding).isActive = true
label.textAlignment = .center
4) Add the panel to your view hierarchy and then add positioning constraints. e.g. hug the right-hand side of a tableViewCell, as in the example image.
Note: you only need to add positional constraints, not dimensional constraints: Auto Layout will solve the layout based on both the intrinsicContentSize of the label and the constraints added earlier.
hostView.addSubview(panel)
panel.translatesAutoresizingMaskIntoConstraints = false
panel.trailingAnchor.constraint(equalTo: hostView.trailingAnchor,
constant: -16).isActive = true
panel.centerYAnchor.constraint(equalTo: hostView.centerYAnchor).isActive = true
add a comment |
up vote
0
down vote
up vote
0
down vote
An elaboration on Mundi's answer.
i.e. embedding a label in a UIView and enforcing padding through Auto Layout. Example:

Overview:
1) Create a UIView ("panel"), and set its appearance.
2) Create a UILabel and add it to the panel.
3) Add constraints to enforce padding.
4) Add the panel to your view hierarchy, then position the panel.
Details:
1) Create the panel view.
let panel = UIView()
panel.backgroundColor = .green
panel.layer.cornerRadius = 12
2) Create the label, add it to the panel as a subview.
let label = UILabel()
panel.addSubview(label)
3) Add constraints between the edges of the label and the panel. This forces the panel to keep a distance from the label. i.e. "padding"
Editorial: doing all this by hand is super-tedious, verbose and error-prone. I suggest you pick an Auto Layout wrapper from github or write one yourself
label.panel.translatesAutoresizingMaskIntoConstraints = false
label.topAnchor.constraint(equalTo: panel.topAnchor,
constant: vPadding).isActive = true
label.bottomAnchor.constraint(equalTo: panel.bottomAnchor,
constant: -vPadding).isActive = true
label.leadingAnchor.constraint(equalTo: panel.leadingAnchor,
constant: hPadding).isActive = true
label.trailingAnchor.constraint(equalTo: panel.trailingAnchor,
constant: -hPadding).isActive = true
label.textAlignment = .center
4) Add the panel to your view hierarchy and then add positioning constraints. e.g. hug the right-hand side of a tableViewCell, as in the example image.
Note: you only need to add positional constraints, not dimensional constraints: Auto Layout will solve the layout based on both the intrinsicContentSize of the label and the constraints added earlier.
hostView.addSubview(panel)
panel.translatesAutoresizingMaskIntoConstraints = false
panel.trailingAnchor.constraint(equalTo: hostView.trailingAnchor,
constant: -16).isActive = true
panel.centerYAnchor.constraint(equalTo: hostView.centerYAnchor).isActive = true
An elaboration on Mundi's answer.
i.e. embedding a label in a UIView and enforcing padding through Auto Layout. Example:

Overview:
1) Create a UIView ("panel"), and set its appearance.
2) Create a UILabel and add it to the panel.
3) Add constraints to enforce padding.
4) Add the panel to your view hierarchy, then position the panel.
Details:
1) Create the panel view.
let panel = UIView()
panel.backgroundColor = .green
panel.layer.cornerRadius = 12
2) Create the label, add it to the panel as a subview.
let label = UILabel()
panel.addSubview(label)
3) Add constraints between the edges of the label and the panel. This forces the panel to keep a distance from the label. i.e. "padding"
Editorial: doing all this by hand is super-tedious, verbose and error-prone. I suggest you pick an Auto Layout wrapper from github or write one yourself
label.panel.translatesAutoresizingMaskIntoConstraints = false
label.topAnchor.constraint(equalTo: panel.topAnchor,
constant: vPadding).isActive = true
label.bottomAnchor.constraint(equalTo: panel.bottomAnchor,
constant: -vPadding).isActive = true
label.leadingAnchor.constraint(equalTo: panel.leadingAnchor,
constant: hPadding).isActive = true
label.trailingAnchor.constraint(equalTo: panel.trailingAnchor,
constant: -hPadding).isActive = true
label.textAlignment = .center
4) Add the panel to your view hierarchy and then add positioning constraints. e.g. hug the right-hand side of a tableViewCell, as in the example image.
Note: you only need to add positional constraints, not dimensional constraints: Auto Layout will solve the layout based on both the intrinsicContentSize of the label and the constraints added earlier.
hostView.addSubview(panel)
panel.translatesAutoresizingMaskIntoConstraints = false
panel.trailingAnchor.constraint(equalTo: hostView.trailingAnchor,
constant: -16).isActive = true
panel.centerYAnchor.constraint(equalTo: hostView.centerYAnchor).isActive = true
edited Nov 9 '17 at 5:14
answered Nov 9 '17 at 3:44
Womble
2,27911925
2,27911925
add a comment |
add a comment |
up vote
0
down vote
Just like other answers but fix a bug.
When label.width is controlled by auto layout, sometimes text will be cropped.
@IBDesignable
class InsetLabel: UILabel {
@IBInspectable var topInset: CGFloat = 4.0
@IBInspectable var leftInset: CGFloat = 4.0
@IBInspectable var bottomInset: CGFloat = 4.0
@IBInspectable var rightInset: CGFloat = 4.0
var insets: UIEdgeInsets {
get {
return UIEdgeInsets.init(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
}
set {
topInset = newValue.top
leftInset = newValue.left
bottomInset = newValue.bottom
rightInset = newValue.right
}
}
override func sizeThatFits(_ size: CGSize) -> CGSize {
var adjSize = super.sizeThatFits(size)
adjSize.width += leftInset + rightInset
adjSize.height += topInset + bottomInset
return adjSize
}
override var intrinsicContentSize: CGSize {
let systemContentSize = super.intrinsicContentSize
let adjustSize = CGSize(width: systemContentSize.width + leftInset + rightInset, height: systemContentSize.height + topInset + bottomInset)
if adjustSize.width > preferredMaxLayoutWidth && preferredMaxLayoutWidth != 0 {
let constraintSize = CGSize(width: bounds.width - (leftInset + rightInset), height: .greatestFiniteMagnitude)
let newSize = super.sizeThatFits(constraintSize)
return CGSize(width: systemContentSize.width, height: ceil(newSize.height) + topInset + bottomInset)
} else {
return adjustSize
}
}
override func drawText(in rect: CGRect) {
super.drawText(in: rect.inset(by: insets))
}
}
add a comment |
up vote
0
down vote
Just like other answers but fix a bug.
When label.width is controlled by auto layout, sometimes text will be cropped.
@IBDesignable
class InsetLabel: UILabel {
@IBInspectable var topInset: CGFloat = 4.0
@IBInspectable var leftInset: CGFloat = 4.0
@IBInspectable var bottomInset: CGFloat = 4.0
@IBInspectable var rightInset: CGFloat = 4.0
var insets: UIEdgeInsets {
get {
return UIEdgeInsets.init(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
}
set {
topInset = newValue.top
leftInset = newValue.left
bottomInset = newValue.bottom
rightInset = newValue.right
}
}
override func sizeThatFits(_ size: CGSize) -> CGSize {
var adjSize = super.sizeThatFits(size)
adjSize.width += leftInset + rightInset
adjSize.height += topInset + bottomInset
return adjSize
}
override var intrinsicContentSize: CGSize {
let systemContentSize = super.intrinsicContentSize
let adjustSize = CGSize(width: systemContentSize.width + leftInset + rightInset, height: systemContentSize.height + topInset + bottomInset)
if adjustSize.width > preferredMaxLayoutWidth && preferredMaxLayoutWidth != 0 {
let constraintSize = CGSize(width: bounds.width - (leftInset + rightInset), height: .greatestFiniteMagnitude)
let newSize = super.sizeThatFits(constraintSize)
return CGSize(width: systemContentSize.width, height: ceil(newSize.height) + topInset + bottomInset)
} else {
return adjustSize
}
}
override func drawText(in rect: CGRect) {
super.drawText(in: rect.inset(by: insets))
}
}
add a comment |
up vote
0
down vote
up vote
0
down vote
Just like other answers but fix a bug.
When label.width is controlled by auto layout, sometimes text will be cropped.
@IBDesignable
class InsetLabel: UILabel {
@IBInspectable var topInset: CGFloat = 4.0
@IBInspectable var leftInset: CGFloat = 4.0
@IBInspectable var bottomInset: CGFloat = 4.0
@IBInspectable var rightInset: CGFloat = 4.0
var insets: UIEdgeInsets {
get {
return UIEdgeInsets.init(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
}
set {
topInset = newValue.top
leftInset = newValue.left
bottomInset = newValue.bottom
rightInset = newValue.right
}
}
override func sizeThatFits(_ size: CGSize) -> CGSize {
var adjSize = super.sizeThatFits(size)
adjSize.width += leftInset + rightInset
adjSize.height += topInset + bottomInset
return adjSize
}
override var intrinsicContentSize: CGSize {
let systemContentSize = super.intrinsicContentSize
let adjustSize = CGSize(width: systemContentSize.width + leftInset + rightInset, height: systemContentSize.height + topInset + bottomInset)
if adjustSize.width > preferredMaxLayoutWidth && preferredMaxLayoutWidth != 0 {
let constraintSize = CGSize(width: bounds.width - (leftInset + rightInset), height: .greatestFiniteMagnitude)
let newSize = super.sizeThatFits(constraintSize)
return CGSize(width: systemContentSize.width, height: ceil(newSize.height) + topInset + bottomInset)
} else {
return adjustSize
}
}
override func drawText(in rect: CGRect) {
super.drawText(in: rect.inset(by: insets))
}
}
Just like other answers but fix a bug.
When label.width is controlled by auto layout, sometimes text will be cropped.
@IBDesignable
class InsetLabel: UILabel {
@IBInspectable var topInset: CGFloat = 4.0
@IBInspectable var leftInset: CGFloat = 4.0
@IBInspectable var bottomInset: CGFloat = 4.0
@IBInspectable var rightInset: CGFloat = 4.0
var insets: UIEdgeInsets {
get {
return UIEdgeInsets.init(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
}
set {
topInset = newValue.top
leftInset = newValue.left
bottomInset = newValue.bottom
rightInset = newValue.right
}
}
override func sizeThatFits(_ size: CGSize) -> CGSize {
var adjSize = super.sizeThatFits(size)
adjSize.width += leftInset + rightInset
adjSize.height += topInset + bottomInset
return adjSize
}
override var intrinsicContentSize: CGSize {
let systemContentSize = super.intrinsicContentSize
let adjustSize = CGSize(width: systemContentSize.width + leftInset + rightInset, height: systemContentSize.height + topInset + bottomInset)
if adjustSize.width > preferredMaxLayoutWidth && preferredMaxLayoutWidth != 0 {
let constraintSize = CGSize(width: bounds.width - (leftInset + rightInset), height: .greatestFiniteMagnitude)
let newSize = super.sizeThatFits(constraintSize)
return CGSize(width: systemContentSize.width, height: ceil(newSize.height) + topInset + bottomInset)
} else {
return adjustSize
}
}
override func drawText(in rect: CGRect) {
super.drawText(in: rect.inset(by: insets))
}
}
edited Nov 9 at 11:21
answered Nov 9 at 9:13
PowHu
1,7721016
1,7721016
add a comment |
add a comment |
up vote
0
down vote
Swift 4+
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.firstLineHeadIndent = 10
// Swift 4.2++
label.attributedText = NSAttributedString(string: "Your text", attributes: [NSAttributedString.Key.paragraphStyle: paragraphStyle])
// Swift 4.1--
label.attributedText = NSAttributedString(string: "Your text", attributes: [NSAttributedStringKey.paragraphStyle: paragraphStyle])
New contributor
Maksim Gridin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
add a comment |
up vote
0
down vote
Swift 4+
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.firstLineHeadIndent = 10
// Swift 4.2++
label.attributedText = NSAttributedString(string: "Your text", attributes: [NSAttributedString.Key.paragraphStyle: paragraphStyle])
// Swift 4.1--
label.attributedText = NSAttributedString(string: "Your text", attributes: [NSAttributedStringKey.paragraphStyle: paragraphStyle])
New contributor
Maksim Gridin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
add a comment |
up vote
0
down vote
up vote
0
down vote
Swift 4+
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.firstLineHeadIndent = 10
// Swift 4.2++
label.attributedText = NSAttributedString(string: "Your text", attributes: [NSAttributedString.Key.paragraphStyle: paragraphStyle])
// Swift 4.1--
label.attributedText = NSAttributedString(string: "Your text", attributes: [NSAttributedStringKey.paragraphStyle: paragraphStyle])
New contributor
Maksim Gridin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
Swift 4+
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.firstLineHeadIndent = 10
// Swift 4.2++
label.attributedText = NSAttributedString(string: "Your text", attributes: [NSAttributedString.Key.paragraphStyle: paragraphStyle])
// Swift 4.1--
label.attributedText = NSAttributedString(string: "Your text", attributes: [NSAttributedStringKey.paragraphStyle: paragraphStyle])
New contributor
Maksim Gridin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
New contributor
Maksim Gridin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
answered yesterday
Maksim Gridin
1
1
New contributor
Maksim Gridin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
New contributor
Maksim Gridin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
Maksim Gridin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f27459746%2fadding-space-padding-to-a-uilabel%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
Possible duplicate of UILabel text margin
– gblazex
Mar 4 '16 at 10:16