【问题标题】:Make a UIView relayout itself when dependent constraint changes当依赖约束发生变化时,自己进行 UIView 重新布局
【发布时间】:2016-12-11 09:35:38
【问题描述】:

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

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

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

【问题讨论】:

  • 查看 Ahmad 的回答,并确保致电 layoutIfNeeded 获取包含 both 您将要更改其位置的视图的 UIView。示例:view.layoutIfNeeded

标签: ios swift uiview nslayoutconstraint


【解决方案1】:
  • 首先:您确定您的所有约束(对于 UIImageview 和 UIButton)都已正确添加吗?

  • 第二:在处理约束时,你应该通过一个约束来改变 UIImageview 的origin.y,通过修改它的constant的值:

而不是直接更改profileImageView.frame.origin.y,您应该更改告诉什么是图像视图origin.y 的约束的constant(如果应用了第一个点,则此约束必须存在...);将此约束作为 IBOutlet 添加到 viewController 并更改其 constant 属性的值(查看代码 sn-p 中的 cmets,这是答案的一部分):

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

希望这会有所帮助。

【讨论】:

  • 谢谢,我只是参考了 UIImageView 的约束,它起作用了。谢谢.....
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多