简体   繁体   中英

Swift | How to add Trailing Space to UILabel programmatically?

I want to add to a UILabel a Trailing space programmatically. At the moment I'm trying this:

let trailingMargin = NSLayoutConstraint(item: myUILabel, attribute: NSLayoutAttribute.TrailingMargin, 
     relatedBy: NSLayoutRelation.Equal, toItem: view, 
     attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 20)

myUILabel.addConstraint( trailingMargin )

But my app always crashes.

myUILabel is in a view and I want that it has a:

Trailing Space to: Superview
Equals: 20

Any advice?

Use it this way:

override func viewDidLoad() {
    super.viewDidLoad()

    let trailingMargin = NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.Trailing,
        relatedBy: NSLayoutRelation.Equal, toItem: myUILabel,
        attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: 20)

    myUILabel.setTranslatesAutoresizingMaskIntoConstraints(false)
    NSLayoutConstraint.activateConstraints([trailingMargin])
}

How to add a trailing space to UILabel text

Although your question is slightly confusing would not this work for you?

func addSpace(inout myLabel : UILabel) {
    self.myLabel.text = "\(self.myLabel.text) "
}

FYI: inout means you are passing by reference - thus the variable passed in can be modified by the function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM