【问题标题】:How to update Height of the view Programmatically?如何以编程方式更新视图的高度?
【发布时间】:2018-04-11 12:44:57
【问题描述】:
我面临的一个问题与自动布局有关。我首先通过自动布局将包含图像视图的视图高度设置为零。但是如果调用了某个函数,我希望将高度更新为一个恒定值,但我的视图高度没有得到更新。
这是代码,我已经在函数内部以编程方式更新了高度,但它不起作用。
let heightContraint = NSLayoutConstraint(item: businessImageView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 40)
businessImageView.addConstraint(heightContraint)
【问题讨论】:
标签:
ios
swift
autolayout
ios-autolayout
【解决方案1】:
首先创建高度约束的IBOutlet。
您只需要更改约束的constant 属性。
例如:
self.consTblFilterHeight.constant = 100.0
self.view.layoutIfNeeded()
将self.view 替换为要更改高度的视图的父视图。
【解决方案2】:
创建你的约束出口,然后像这样设置它:
- self.heightConstraintOutlet.constant = newHeightValue
【解决方案3】:
businessImageView.addConstraint(heightContraint) 不是更新约束的代码。它增加了一个约束。
为了更新父视图(有图像)的高度,您需要更新 businessImageView 的 高度约束的常量。
businessImageView.heightConstraint.constant = 40
self.view.layoutIfNeeded()
【解决方案4】:
方法
代码
heightConstraint.isActive = true
heightConstraint.constant = 20