Adding space/padding to a UILabel











up vote
108
down vote

favorite
35












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:



enter image description here



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:



enter image description here










share|improve this question




















  • 1




    Possible duplicate of UILabel text margin
    – gblazex
    Mar 4 '16 at 10:16















up vote
108
down vote

favorite
35












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:



enter image description here



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:



enter image description here










share|improve this question




















  • 1




    Possible duplicate of UILabel text margin
    – gblazex
    Mar 4 '16 at 10:16













up vote
108
down vote

favorite
35









up vote
108
down vote

favorite
35






35





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:



enter image description here



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:



enter image description here










share|improve this question















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:



enter image description here



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:



enter image description here







ios uilabel padding






share|improve this question















share|improve this question













share|improve this question




share|improve this question








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














  • 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












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






share|improve this answer























  • 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




















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'





share|improve this answer



















  • 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 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


















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
}
}
}





share|improve this answer























  • 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


















up vote
61
down vote













You can do it properly from IB :




  1. change the text to attributed


attributed text




  1. go to dropdown list with "..."


enter image description here




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


enter image description here




  1. check the result


enter image description here






share|improve this answer

















  • 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


















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
}
}





share|improve this answer























  • 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


















up vote
32
down vote













Just use a UIView as a superview and define a fixed margin to the label with auto layout.






share|improve this answer

















  • 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






  • 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




















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





share|improve this answer



















  • 1




    Hey this is a great tip! No extensions required! :-D
    – Felipe Ferri
    Aug 16 '17 at 14:35






  • 1




    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










  • 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


















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:








share|improve this answer





















  • 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


















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!






share|improve this answer




























    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))
    }
    }





    share|improve this answer




























      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.






      share|improve this answer





















      • 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


















      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:



      padding label with wrong intrinsic content size



      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:



      padding label with right intrinsic content size



      I hope to help some people in the same situation as me.






      share|improve this answer



















      • 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




















      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)
      }
      }





      share|improve this answer























      • 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


















      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))
      }

      }





      share|improve this answer




























        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)))
        }

        }





        share|improve this answer




























          up vote
          2
          down vote













          Another option without subclassing would be to:




          1. Set label text

          2. sizeToFit()


          3. 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)







          share|improve this answer























          • 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


















          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.
          }

          }





          share|improve this answer






























            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)





            share|improve this answer




























              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)
              }
              }





              share|improve this answer




























                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)
                }
                }





                share|improve this answer























                • 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


















                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)))
                }

                }





                share|improve this answer





















                • 3.0 version on bottom page
                  – odemolliens
                  Oct 10 '16 at 11:59


















                up vote
                0
                down vote













                Just use autolayout:



                let paddedWidth = myLabel.intrinsicContentSize.width + 2 * padding
                myLabel.widthAnchor.constraint(equalToConstant: paddedWidth).isActive = true


                Done.






                share|improve this answer




























                  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))
                  }
                  }





                  share|improve this answer




























                    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.






                    share|improve this answer




























                      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:



                      looks like a padded UILabel



                      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





                      share|improve this answer






























                        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))
                        }
                        }





                        share|improve this answer






























                          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])





                          share|improve this answer








                          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.


















                            Your Answer






                            StackExchange.ifUsing("editor", function () {
                            StackExchange.using("externalEditor", function () {
                            StackExchange.using("snippets", function () {
                            StackExchange.snippets.init();
                            });
                            });
                            }, "code-snippets");

                            StackExchange.ready(function() {
                            var channelOptions = {
                            tags: "".split(" "),
                            id: "1"
                            };
                            initTagRenderer("".split(" "), "".split(" "), channelOptions);

                            StackExchange.using("externalEditor", function() {
                            // Have to fire editor after snippets, if snippets enabled
                            if (StackExchange.settings.snippets.snippetsEnabled) {
                            StackExchange.using("snippets", function() {
                            createEditor();
                            });
                            }
                            else {
                            createEditor();
                            }
                            });

                            function createEditor() {
                            StackExchange.prepareEditor({
                            heartbeatType: 'answer',
                            convertImagesToLinks: true,
                            noModals: true,
                            showLowRepImageUploadWarning: true,
                            reputationToPostImages: 10,
                            bindNavPrevention: true,
                            postfix: "",
                            imageUploader: {
                            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                            allowUrls: true
                            },
                            onDemand: true,
                            discardSelector: ".discard-answer"
                            ,immediatelyShowMarkdownHelp:true
                            });


                            }
                            });














                            draft saved

                            draft discarded


















                            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

























                            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






                            share|improve this answer























                            • 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

















                            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






                            share|improve this answer























                            • 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















                            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






                            share|improve this answer














                            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







                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            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




















                            • 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














                            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'





                            share|improve this answer



















                            • 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 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















                            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'





                            share|improve this answer



















                            • 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 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













                            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'





                            share|improve this answer














                            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'






                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            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 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














                            • 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 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








                            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










                            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
                            }
                            }
                            }





                            share|improve this answer























                            • 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















                            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
                            }
                            }
                            }





                            share|improve this answer























                            • 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













                            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
                            }
                            }
                            }





                            share|improve this answer














                            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
                            }
                            }
                            }






                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            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


















                            • 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










                            up vote
                            61
                            down vote













                            You can do it properly from IB :




                            1. change the text to attributed


                            attributed text




                            1. go to dropdown list with "..."


                            enter image description here




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


                            enter image description here




                            1. check the result


                            enter image description here






                            share|improve this answer

















                            • 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















                            up vote
                            61
                            down vote













                            You can do it properly from IB :




                            1. change the text to attributed


                            attributed text




                            1. go to dropdown list with "..."


                            enter image description here




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


                            enter image description here




                            1. check the result


                            enter image description here






                            share|improve this answer

















                            • 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













                            up vote
                            61
                            down vote










                            up vote
                            61
                            down vote









                            You can do it properly from IB :




                            1. change the text to attributed


                            attributed text




                            1. go to dropdown list with "..."


                            enter image description here




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


                            enter image description here




                            1. check the result


                            enter image description here






                            share|improve this answer












                            You can do it properly from IB :




                            1. change the text to attributed


                            attributed text




                            1. go to dropdown list with "..."


                            enter image description here




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


                            enter image description here




                            1. check the result


                            enter image description here







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            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














                            • 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










                            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
                            }
                            }





                            share|improve this answer























                            • 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















                            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
                            }
                            }





                            share|improve this answer























                            • 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













                            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
                            }
                            }





                            share|improve this answer














                            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
                            }
                            }






                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            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


















                            • 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










                            up vote
                            32
                            down vote













                            Just use a UIView as a superview and define a fixed margin to the label with auto layout.






                            share|improve this answer

















                            • 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






                            • 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

















                            up vote
                            32
                            down vote













                            Just use a UIView as a superview and define a fixed margin to the label with auto layout.






                            share|improve this answer

















                            • 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






                            • 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















                            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.






                            share|improve this answer












                            Just use a UIView as a superview and define a fixed margin to the label with auto layout.







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Dec 13 '14 at 16:20









                            Mundi

                            69.3k1693120




                            69.3k1693120








                            • 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






                            • 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




                              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




                              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












                            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





                            share|improve this answer



















                            • 1




                              Hey this is a great tip! No extensions required! :-D
                              – Felipe Ferri
                              Aug 16 '17 at 14:35






                            • 1




                              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










                            • 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















                            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





                            share|improve this answer



















                            • 1




                              Hey this is a great tip! No extensions required! :-D
                              – Felipe Ferri
                              Aug 16 '17 at 14:35






                            • 1




                              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










                            • 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













                            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





                            share|improve this answer














                            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






                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            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




                              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










                            • 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




                              Hey this is a great tip! No extensions required! :-D
                              – Felipe Ferri
                              Aug 16 '17 at 14:35






                            • 1




                              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










                            • 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










                            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:








                            share|improve this answer





















                            • 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















                            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:








                            share|improve this answer





















                            • 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













                            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:








                            share|improve this answer












                            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:









                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            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


















                            • 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










                            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!






                            share|improve this answer

























                              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!






                              share|improve this answer























                                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!






                                share|improve this answer












                                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!







                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered Jan 28 '17 at 19:42









                                mriaz0011

                                1,333156




                                1,333156






















                                    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))
                                    }
                                    }





                                    share|improve this answer

























                                      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))
                                      }
                                      }





                                      share|improve this answer























                                        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))
                                        }
                                        }





                                        share|improve this answer












                                        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))
                                        }
                                        }






                                        share|improve this answer












                                        share|improve this answer



                                        share|improve this answer










                                        answered Feb 4 '17 at 21:52









                                        andrewz

                                        1,74532544




                                        1,74532544






















                                            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.






                                            share|improve this answer





















                                            • 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















                                            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.






                                            share|improve this answer





















                                            • 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













                                            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.






                                            share|improve this answer












                                            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.







                                            share|improve this answer












                                            share|improve this answer



                                            share|improve this answer










                                            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


















                                            • 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










                                            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:



                                            padding label with wrong intrinsic content size



                                            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:



                                            padding label with right intrinsic content size



                                            I hope to help some people in the same situation as me.






                                            share|improve this answer



















                                            • 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

















                                            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:



                                            padding label with wrong intrinsic content size



                                            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:



                                            padding label with right intrinsic content size



                                            I hope to help some people in the same situation as me.






                                            share|improve this answer



















                                            • 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















                                            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:



                                            padding label with wrong intrinsic content size



                                            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:



                                            padding label with right intrinsic content size



                                            I hope to help some people in the same situation as me.






                                            share|improve this answer














                                            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:



                                            padding label with wrong intrinsic content size



                                            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:



                                            padding label with right intrinsic content size



                                            I hope to help some people in the same situation as me.







                                            share|improve this answer














                                            share|improve this answer



                                            share|improve this answer








                                            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) 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
















                                            • 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










                                            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












                                            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)
                                            }
                                            }





                                            share|improve this answer























                                            • 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















                                            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)
                                            }
                                            }





                                            share|improve this answer























                                            • 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













                                            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)
                                            }
                                            }





                                            share|improve this answer














                                            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)
                                            }
                                            }






                                            share|improve this answer














                                            share|improve this answer



                                            share|improve this answer








                                            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


















                                            • 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










                                            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))
                                            }

                                            }





                                            share|improve this answer

























                                              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))
                                              }

                                              }





                                              share|improve this answer























                                                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))
                                                }

                                                }





                                                share|improve this answer












                                                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))
                                                }

                                                }






                                                share|improve this answer












                                                share|improve this answer



                                                share|improve this answer










                                                answered May 29 '17 at 10:05









                                                SanRam

                                                41167




                                                41167






















                                                    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)))
                                                    }

                                                    }





                                                    share|improve this answer

























                                                      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)))
                                                      }

                                                      }





                                                      share|improve this answer























                                                        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)))
                                                        }

                                                        }





                                                        share|improve this answer












                                                        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)))
                                                        }

                                                        }






                                                        share|improve this answer












                                                        share|improve this answer



                                                        share|improve this answer










                                                        answered Oct 10 '16 at 9:55









                                                        odemolliens

                                                        1,91622225




                                                        1,91622225






















                                                            up vote
                                                            2
                                                            down vote













                                                            Another option without subclassing would be to:




                                                            1. Set label text

                                                            2. sizeToFit()


                                                            3. 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)







                                                            share|improve this answer























                                                            • 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















                                                            up vote
                                                            2
                                                            down vote













                                                            Another option without subclassing would be to:




                                                            1. Set label text

                                                            2. sizeToFit()


                                                            3. 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)







                                                            share|improve this answer























                                                            • 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













                                                            up vote
                                                            2
                                                            down vote










                                                            up vote
                                                            2
                                                            down vote









                                                            Another option without subclassing would be to:




                                                            1. Set label text

                                                            2. sizeToFit()


                                                            3. 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)







                                                            share|improve this answer














                                                            Another option without subclassing would be to:




                                                            1. Set label text

                                                            2. sizeToFit()


                                                            3. 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)








                                                            share|improve this answer














                                                            share|improve this answer



                                                            share|improve this answer








                                                            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


















                                                            • 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










                                                            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.
                                                            }

                                                            }





                                                            share|improve this answer



























                                                              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.
                                                              }

                                                              }





                                                              share|improve this answer

























                                                                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.
                                                                }

                                                                }





                                                                share|improve this answer














                                                                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.
                                                                }

                                                                }






                                                                share|improve this answer














                                                                share|improve this answer



                                                                share|improve this answer








                                                                edited Apr 21 '15 at 3:47









                                                                Shashank Agarwal

                                                                1,7531419




                                                                1,7531419










                                                                answered Apr 21 '15 at 3:08









                                                                Alex Freitas

                                                                112




                                                                112






















                                                                    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)





                                                                    share|improve this answer

























                                                                      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)





                                                                      share|improve this answer























                                                                        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)





                                                                        share|improve this answer












                                                                        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)






                                                                        share|improve this answer












                                                                        share|improve this answer



                                                                        share|improve this answer










                                                                        answered Oct 26 '17 at 4:59









                                                                        zsong

                                                                        44.7k21129188




                                                                        44.7k21129188






















                                                                            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)
                                                                            }
                                                                            }





                                                                            share|improve this answer

























                                                                              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)
                                                                              }
                                                                              }





                                                                              share|improve this answer























                                                                                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)
                                                                                }
                                                                                }





                                                                                share|improve this answer












                                                                                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)
                                                                                }
                                                                                }






                                                                                share|improve this answer












                                                                                share|improve this answer



                                                                                share|improve this answer










                                                                                answered Sep 18 at 14:27









                                                                                Simon Backx

                                                                                646713




                                                                                646713






















                                                                                    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)
                                                                                    }
                                                                                    }





                                                                                    share|improve this answer























                                                                                    • 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















                                                                                    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)
                                                                                    }
                                                                                    }





                                                                                    share|improve this answer























                                                                                    • 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













                                                                                    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)
                                                                                    }
                                                                                    }





                                                                                    share|improve this answer














                                                                                    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)
                                                                                    }
                                                                                    }






                                                                                    share|improve this answer














                                                                                    share|improve this answer



                                                                                    share|improve this answer








                                                                                    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


















                                                                                    • 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










                                                                                    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)))
                                                                                    }

                                                                                    }





                                                                                    share|improve this answer





















                                                                                    • 3.0 version on bottom page
                                                                                      – odemolliens
                                                                                      Oct 10 '16 at 11:59















                                                                                    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)))
                                                                                    }

                                                                                    }





                                                                                    share|improve this answer





















                                                                                    • 3.0 version on bottom page
                                                                                      – odemolliens
                                                                                      Oct 10 '16 at 11:59













                                                                                    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)))
                                                                                    }

                                                                                    }





                                                                                    share|improve this answer












                                                                                    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)))
                                                                                    }

                                                                                    }






                                                                                    share|improve this answer












                                                                                    share|improve this answer



                                                                                    share|improve this answer










                                                                                    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


















                                                                                    • 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










                                                                                    up vote
                                                                                    0
                                                                                    down vote













                                                                                    Just use autolayout:



                                                                                    let paddedWidth = myLabel.intrinsicContentSize.width + 2 * padding
                                                                                    myLabel.widthAnchor.constraint(equalToConstant: paddedWidth).isActive = true


                                                                                    Done.






                                                                                    share|improve this answer

























                                                                                      up vote
                                                                                      0
                                                                                      down vote













                                                                                      Just use autolayout:



                                                                                      let paddedWidth = myLabel.intrinsicContentSize.width + 2 * padding
                                                                                      myLabel.widthAnchor.constraint(equalToConstant: paddedWidth).isActive = true


                                                                                      Done.






                                                                                      share|improve this answer























                                                                                        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.






                                                                                        share|improve this answer












                                                                                        Just use autolayout:



                                                                                        let paddedWidth = myLabel.intrinsicContentSize.width + 2 * padding
                                                                                        myLabel.widthAnchor.constraint(equalToConstant: paddedWidth).isActive = true


                                                                                        Done.







                                                                                        share|improve this answer












                                                                                        share|improve this answer



                                                                                        share|improve this answer










                                                                                        answered Mar 7 '17 at 22:17









                                                                                        Tim Shadel

                                                                                        1,20011214




                                                                                        1,20011214






















                                                                                            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))
                                                                                            }
                                                                                            }





                                                                                            share|improve this answer

























                                                                                              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))
                                                                                              }
                                                                                              }





                                                                                              share|improve this answer























                                                                                                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))
                                                                                                }
                                                                                                }





                                                                                                share|improve this answer












                                                                                                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))
                                                                                                }
                                                                                                }






                                                                                                share|improve this answer












                                                                                                share|improve this answer



                                                                                                share|improve this answer










                                                                                                answered Mar 17 '17 at 10:52









                                                                                                Pelanes

                                                                                                2,82712529




                                                                                                2,82712529






















                                                                                                    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.






                                                                                                    share|improve this answer

























                                                                                                      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.






                                                                                                      share|improve this answer























                                                                                                        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.






                                                                                                        share|improve this answer












                                                                                                        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.







                                                                                                        share|improve this answer












                                                                                                        share|improve this answer



                                                                                                        share|improve this answer










                                                                                                        answered Apr 21 '17 at 21:44









                                                                                                        pks1981

                                                                                                        11




                                                                                                        11






















                                                                                                            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:



                                                                                                            looks like a padded UILabel



                                                                                                            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





                                                                                                            share|improve this answer



























                                                                                                              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:



                                                                                                              looks like a padded UILabel



                                                                                                              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





                                                                                                              share|improve this answer

























                                                                                                                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:



                                                                                                                looks like a padded UILabel



                                                                                                                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





                                                                                                                share|improve this answer














                                                                                                                An elaboration on Mundi's answer.



                                                                                                                i.e. embedding a label in a UIView and enforcing padding through Auto Layout. Example:



                                                                                                                looks like a padded UILabel



                                                                                                                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






                                                                                                                share|improve this answer














                                                                                                                share|improve this answer



                                                                                                                share|improve this answer








                                                                                                                edited Nov 9 '17 at 5:14

























                                                                                                                answered Nov 9 '17 at 3:44









                                                                                                                Womble

                                                                                                                2,27911925




                                                                                                                2,27911925






















                                                                                                                    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))
                                                                                                                    }
                                                                                                                    }





                                                                                                                    share|improve this answer



























                                                                                                                      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))
                                                                                                                      }
                                                                                                                      }





                                                                                                                      share|improve this answer

























                                                                                                                        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))
                                                                                                                        }
                                                                                                                        }





                                                                                                                        share|improve this answer














                                                                                                                        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))
                                                                                                                        }
                                                                                                                        }






                                                                                                                        share|improve this answer














                                                                                                                        share|improve this answer



                                                                                                                        share|improve this answer








                                                                                                                        edited Nov 9 at 11:21

























                                                                                                                        answered Nov 9 at 9:13









                                                                                                                        PowHu

                                                                                                                        1,7721016




                                                                                                                        1,7721016






















                                                                                                                            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])





                                                                                                                            share|improve this answer








                                                                                                                            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.






















                                                                                                                              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])





                                                                                                                              share|improve this answer








                                                                                                                              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.




















                                                                                                                                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])





                                                                                                                                share|improve this answer








                                                                                                                                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])






                                                                                                                                share|improve this answer








                                                                                                                                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.









                                                                                                                                share|improve this answer



                                                                                                                                share|improve this answer






                                                                                                                                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.






























                                                                                                                                    draft saved

                                                                                                                                    draft discarded




















































                                                                                                                                    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.




                                                                                                                                    draft saved


                                                                                                                                    draft discarded














                                                                                                                                    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





















































                                                                                                                                    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







                                                                                                                                    Popular posts from this blog

                                                                                                                                    The Sandy Post

                                                                                                                                    Danny Elfman

                                                                                                                                    Pages that link to "Head v. Amoskeag Manufacturing Co."