简体   繁体   English

斯威夫特| 如何以编程方式将尾随空间添加到UILabel?

[英]Swift | How to add Trailing Space to UILabel programmatically?

I want to add to a UILabel a Trailing space programmatically. 我想以编程方式向UILabel添加尾随空间。 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: myUILabel在视图中,我希望它具有:

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 如何在UILabel文本中添加尾随空格

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 仅供参考: inout表示您正在通过引用传递-因此传入的变量可以由函数修改

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何以编程方式在Swift 3中将UILabel添加到UICollectionViewCell - How to programmatically add a UILabel to UICollectionViewCell in Swift 3 UILabel - 如何在Swift 3中的行之间添加空格 - UILabel - How to add space between lines in Swift 3 Swift & UILabel:如何以编程方式在 Swift 中添加填充和边距? - Swift & UILabel : How to add padding and margin in Swift programmatically? UIlabel尾随空间不起作用 - UIlabel trailing space not working Swift 3以编程方式创建UILabel并添加NSLayoutConstraints - Swift 3 Create UILabel programmatically and add NSLayoutConstraints 在 Swift 4 中以编程方式将 UIImageView、UILabel 添加到 UIStackView - Add UIImageView, UILabel to UIStackView programmatically in Swift 4 如何在 Swift 中以编程方式调整 UILabel 行间距? - How to adjust a UILabel line spacing programmatically in Swift? 如何使用 Swift 以编程方式创建 UILabel? - How to create UILabel programmatically using Swift? 如何在 Swift 中以编程方式为 UILabel 提供动态高度? - How to give dynamic height to UILabel programmatically in Swift? 如何在 Swift 中以编程方式在 UILabel 中插入自定义表情符号? - How to insert custom emoji in UILabel programmatically, in Swift?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM