当依赖约束更改时,使 UIView 重新布局自身



我有一个UIImageViewUIButtonUIButtonUIImageView的顶部对齐。现在在代码中,我正在更改UIImageView的顶部,但UIButton没有相应地更新。我试了SetNeedsLayoutLayoutIfNeededUIButton但没有任何效果。

override func viewDidLayoutSubviews() {
profileImageView.frame.origin.y = arcView.bounds.height/1.8
editProfileButton.layer.setNeedsDisplay()
}

我已经在故事板中设置了约束。我真的很感激这里的任何帮助。

  • 首先:你确定你所有的约束(对于UIImageview和UIButton)都添加了正确吗?

  • 第二:在处理约束时,还应通过约束来更改 UIImageview 的origin.y,方法是修改其常量的值:

与其直接更改profileImageView.frame.origin.y,不如更改说明图像视图origin.y是什么的约束的constant(如果应用了第一个点,则此约束必须存在......将此约束作为IBOutlet添加到 viewController 中,并更改其constant属性的值(看看代码片段中的注释,这是答案的一部分):

class ViewController: UIViewController {
// let's assume that this is the @IBOutlet of the constraint, I called it 'imageViewTopMargin':
@IBOutlet weak var imageViewTopMargin: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
// it's not necessary -for sure- to do this the in the viewDidLoad method
// but I'm doing this for demo purposes:
// let's say that you want to push the imageView to the bottom with extra 40 points:
imageViewTopMargin.constant += 40
}
}

希望这有帮助。

最新更新