问题描述
我在代码中有一个 UIImage
,我想在按下按钮时垂直放大。 UIImage
在故事板中完全受限制,我想在按下按钮时更改其高度。
I have a UIImage
in code that I would like to enlarge vertically when a button is pressed. The UIImage
is fully constrained in the storyboard and I would like to change its height when the button is pressed.
我在代码中链接了 UIImage
及其高度约束:
I have linked the UIImage
and its height constraint in the code:
@IBOutlet weak var botBotCons: NSLayoutConstraint!
@IBOutlet weak var botBot: UIImageView!
然后
@IBAction func testButton(sender: UIBarButtonItem) {
println("testButton pressed")
self.botBotCons.constant = 68 //or +=62 as its current constant is 6
self.view.layoutIfNeeded()
}
我得到 testButton在控制台中按下消息,但图像不会调整大小。我究竟做错了什么?我是否还需要在故事板中更改某些内容?
I get the testButton pressed message in the console, but the image doesn't resize. What am I doing wrong? Do I need to change something in the storyboard as well?
推荐答案
您应该调用 layoutIfNeeded
在动画块中。 Apple实际上建议您在动画块之前调用一次,以确保所有挂起的布局操作都已完成。我只是通过调整按钮大小来检查它 - 一切正常。
You should to call layoutIfNeeded
within the animation block. Apple actually recommends you call it once before the animation block to ensure that all pending layout operations have been completed. I just checked it with the resizing of button - everything works fine.
@IBOutlet weak var myBtn: UIButton!
@IBOutlet weak var btnHeight: NSLayoutConstraint!
@IBOutlet weak var btnWidth: NSLayoutConstraint!
@IBAction func resizeBtn(sender: AnyObject) {
self.myBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0)
self.view.layoutIfNeeded()
self.btnHeight.constant += 50
self.btnWidth.constant += 50
UIView.animateWithDuration(0.7, animations: {
self.view.layoutIfNeeded()
})
}
PS确保其他约束不会阻止您的更改。
P.S. make sure that other constraints don't block your changes.
这篇关于使用代码更新故事板约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!