在运行时调整UIView的大小

时间:2018-04-17 08:31:52

标签: ios swift

我有一个UIView,它在我的故事板中垂直和水平居中,并具有固定的高度(100)宽度(300)。现在我希望uiview在运行时调整大小(100,100)

到目前为止,我已经尝试了这一点,但没有任何效果。

let cgRect = CGRect(x: 0, y: 0, width: 100, height: 100)

sampleView.draw(cgRect)

sampleView.frame = CGRect(x: 0, y: 0, width: 100, height: 100)

sampleView.frame.size.height = 100
sampleView.frame.size.width = 100

3 个答案:

答案 0 :(得分:2)

将宽度和高度约束挂钩为IBOutlet并在

@IBAction func btnClicked(_ sender: Any) {

    self.widthCon.constant = 100

    self.heightCon.constant = 100

    self.view.layoutIfNeeded()
}

答案 1 :(得分:0)

要通过按钮更改运行时期间的约束,您需要将其添加到IBAction。为了动画更改而不是仅仅跳转,请将代码放入UIView 动画方法中:

@IBAction func buttonPressed() {

    self.widthCon.constant = 100

    self.heightCon.constant = 100

    UIView.animate(withDuration: 0.3, animations: {
        self.view.layoutIfNeeded()
    })
}

答案 2 :(得分:0)

你可以这样做:

override func layoutSubviews() {
    super.layoutSubviews()
    // set hight and width by constraints.
}

或:

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    // set hight and width by constraints.
}
相关问题