is there is a way to create constraint greater than or equal relation through code

偶尔善良 提交于 2020-02-05 03:59:11

问题


I'm working on expandable table cell, and my algorithm is follow:

  1. I create two views.
  2. Create the height constraint of second view, drag it as IBOutlet to my cell.
  3. When cell is selected change status of selected cell.

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.

Here are my constraints:

So, my question is:

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.


回答1:


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
)

Alternatively, you can do it like this:

let heightConstraint = yourExpandableView.heightAnchor.constraint(greaterThanOrEqualToConstant: 120)

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.

I hope it's helpful!



来源:https://stackoverflow.com/questions/44305834/is-there-is-a-way-to-create-constraint-greater-than-or-equal-relation-through-co

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!