iOS Swift 标签框高度未正确更新
iOS Swift Label Frame Height Not Updating Correctly
我有一个标签,每次用户单击按钮时其文本都会发生变化。但是,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!!
}
总而言之,这就是正在发生的事情:
用户点击Button,Label显示新文字,但frame.height没有变化。
用户再次点击 Button,Label 文本再次更改,frame.height 这次更新,但更新到它应该在步骤 1 中具有的旧值。
我是 Swift 的新手,如有任何帮助,我们将不胜感激。
当 iOS 动画调整大小时,它实际上首先更改显示层,然后更改对象的实际框架(或大致沿着这些线)。
尝试查询 Label.layer.frame.height
尝试调用 Label.sizeToFit()
以强制重绘,然后再进行第二个 print
调用。
或者,您可以等待几刻,直到 iOS 自己完成:
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 10000000), dispatch_get_main_queue(), {
print("2. Height = ", self.Label.frame.height) //Returns the correct height
})
更改文本后立即调用这些方法
label.setNeedsLayout()
label.layoutIfNeeded()
这将为您提供正确的框架。
我有一个标签,每次用户单击按钮时其文本都会发生变化。但是,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!!
}
总而言之,这就是正在发生的事情:
用户点击Button,Label显示新文字,但frame.height没有变化。
用户再次点击 Button,Label 文本再次更改,frame.height 这次更新,但更新到它应该在步骤 1 中具有的旧值。
我是 Swift 的新手,如有任何帮助,我们将不胜感激。
当 iOS 动画调整大小时,它实际上首先更改显示层,然后更改对象的实际框架(或大致沿着这些线)。
尝试查询 Label.layer.frame.height
尝试调用 Label.sizeToFit()
以强制重绘,然后再进行第二个 print
调用。
或者,您可以等待几刻,直到 iOS 自己完成:
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 10000000), dispatch_get_main_queue(), {
print("2. Height = ", self.Label.frame.height) //Returns the correct height
})
更改文本后立即调用这些方法
label.setNeedsLayout()
label.layoutIfNeeded()
这将为您提供正确的框架。