簡體   English   中英

斯威夫特| 如何以編程方式將尾隨空間添加到UILabel?

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

我想以編程方式向UILabel添加尾隨空間。 目前,我正在嘗試這樣做:

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

myUILabel.addConstraint( trailingMargin )

但是我的應用程序總是崩潰。

myUILabel在視圖中,我希望它具有:

Trailing Space to: Superview
Equals: 20

有什么建議嗎?

使用這種方式:

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

如何在UILabel文本中添加尾隨空格

盡管您的問題有點令人困惑,但這對您來說行不通嗎?

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

僅供參考: inout表示您正在通過引用傳遞-因此傳入的變量可以由函數修改

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM