有没有一种方法可以通过代码创建大于或等于关系的约束 [英] Is there is a way to create constraint greater than or equal relation through code
问题描述
我正在处理可扩展表格单元格,我的算法如下:
I'm working on expandable table cell, and my algorithm is follow:
- 我创建两个视图.
- 创建第二个视图的高度约束,将其作为IBOutlet拖动到我的单元格中.
- 选中单元格后,更改所选单元格的状态.
class ExpandableCell: UITableViewCell {
@IBOutlet weak var expandableCellHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var expandableView: UIView!
var isExpanded:Bool = false
{
didSet
{
if !isExpanded {
self.expandableCellHeightConstraint.constant = 0.0
} else {
self.expandableCellHeightConstraint.constant = 120
}
}
}
}
一切都很好,但是我希望我的第二个视图调整与内部内容相关的大小.
Everything is fine, but I want my second view resize related to inner content.
这是我的限制条件:
所以,我的问题是:
将非严格值写入self.expandableCellHeightConstraint.constant
的最佳方法是什么?实际上,我曾想过编写self.expandableCellHeightConstraint.constant >= 120
之类的东西,但据我所知,这是不可能的.
What is the best way to write non-strict value to self.expandableCellHeightConstraint.constant
? Actually I thought of writing something like self.expandableCellHeightConstraint.constant >= 120
, but as far as I get it is impossible.
推荐答案
As Martin R suggests, you can create the height constraint in code like this:
let heightConstraint = NSLayoutConstraint(
item: yourExpandableView,
attribute: .height,
relatedBy: .greaterThanOrEqual,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1.0,
constant: 120
)
或者,您也可以这样:
let heightConstraint = yourExpandableView.heightAnchor.constraint(greaterThanOrEqualToConstant: 120)
然后,当需要启用/禁用此约束时,可以将其isActive
属性设置为true或false.您可能还希望将此约束保留为类的属性,因为一旦将约束的属性isActive
设置为false,约束就会变为nil.
Then you can set its isActive
property to true or false whenever you need to enable/disable this constraint. You probably also want to hold this constraint as a property of the class, because constraints become nil, once their property isActive
is set to false.
希望对您有所帮助!
这篇关于有没有一种方法可以通过代码创建大于或等于关系的约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!