Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you add inset to UILabel (iOS Swift)?

Tags:

I am an Android developer learning iOS. How do you add padding (inset) to UILabel in iOS Swift? I have not been successful at finding an easy tutorial on this. Thank you.

Also, how can I add margins to UI elements in Swift? When I try the below, nothing gets updated (upon hitting "add constraint").

enter image description here

like image 562
andyjslee Avatar asked Aug 27 '15 01:08

andyjslee


People also ask

How do you add an inset to UILabel?

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. You could additionally provide your new subclassed UILabel with insets variables for TOP, LEFT, BOTTOM and RIGHT.

How do I add padding to UILabel Swift?

If you have created an UILabel programmatically, replace the UILabel class with the PaddingLabel and add the padding: // Init Label let label = PaddingLabel() label. backgroundColor = . black label.

What is UILabel in Swift?

A view that displays one or more lines of informational text.

How do I set padding in Xcode?

These methods just allow you to add a rect (frame) to your textfield's label. newBounds method create the rect (frame) that will be added to textfield's label. Finally your padding is: let padding = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5);


2 Answers

This is the code you need to add in Swift 3:

class InsetLabel: UILabel {
    let topInset = CGFloat(0)
    let bottomInset = CGFloat(0)
    let leftInset = CGFloat(20)
    let rightInset = CGFloat(20)

    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 intrinsicSuperViewContentSize = super.intrinsicContentSize
        intrinsicSuperViewContentSize.height += topInset + bottomInset
        intrinsicSuperViewContentSize.width += leftInset + rightInset
        return intrinsicSuperViewContentSize
    }
}
like image 172
arauter Avatar answered Oct 21 '22 13:10

arauter


Probably the best idea is to subclass UILabel and override drawTextInRect: like this:

class InsetLabel: UILabel {
    override func drawTextInRect(rect: CGRect) {
        super.drawTextInRect(UIEdgeInsetsInsetRect(rect, UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)))
    }
}

SWIFT 4+:

class InsetLabel: UILabel {
    override func drawText(in rect: CGRect) {
        super.drawText(in: rect.inset(by: UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)))
    }
}
like image 33
Sebyddd Avatar answered Oct 21 '22 14:10

Sebyddd