iOS Swift标签框架高度未正确更新

dim*_*006 3 height label frame ios swift

我有一个Label,每次用户单击Button时,其文本都会更改。但是,即使Label内容已更改,Label.frame.height值也不会立即更新。更改Label的函数在多个位置调用,但是高度仅在@IBAction块内部更新,其值滞后一个单击周期。我的代码如下:

func changeLabelText() {
//Here I have an algorithm (not shown) that generates myMutableString 
Label.attributedText = myMutableString  //Label is updated.
}


@IBAction func changeLabelButton(sender: UIButton) {
print("1. Height = ", Label.frame.height) //Height updates here, but it's the old value.  
changeLabelText()  //Label is updated.
print("2. Height = ", Label.frame.height) //Returns same height as Line 1!!
}


override func viewDidLoad() {
super.viewDidLoad()
print("3. Height = ", Label.frame.height) //Initially, height is 21.0 when ViewController first loads.
changeLabelText() //Label is updated.
print("4. Height = ", Label.frame.height) //Returns height = 21.0, even though simulator shows Label updated!!
}
Run Code Online (Sandbox Code Playgroud)

总而言之,这是正在发生的事情:

  1. 用户单击“按钮”,“标签”显示新文本,但frame.height不变。

  2. 用户再次单击“按钮”,“标签”文本再次更改,“ frame.height”这次更新,但是更新为在步骤1中应具有的旧值。

我是Swift的新手,对此提供的任何帮助都值得赞赏。

pau*_*lvs 5

更改文本后立即调用这些方法

label.setNeedsLayout()
label.layoutIfNeeded()
Run Code Online (Sandbox Code Playgroud)

这将为您提供正确的框架。

  • .layoutIfNeeded() 似乎解决了我的问题。太感谢了! (2认同)