Update storyboard constraint using code

女生的网名这么多〃 提交于 2019-12-02 10:33:10

问题


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.

I have linked the UIImage and its height constraint in the code:

    @IBOutlet weak var botBotCons: NSLayoutConstraint!
    @IBOutlet weak var botBot: UIImageView!

Then

@IBAction func testButton(sender: UIBarButtonItem) {
    println("testButton pressed")
    self.botBotCons.constant = 68   //or +=62 as its current constant is 6
    self.view.layoutIfNeeded()
}

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?


回答1:


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

P.S. make sure that other constraints don't block your changes.



来源:https://stackoverflow.com/questions/32133574/update-storyboard-constraint-using-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!