快速设置约束条件的优先级 [英] Set priority on constraints in swift

查看:324
本文介绍了快速设置约束条件的优先级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在努力以编程方式迅速解决约束问题。

I've been struggling to make priority on constraints work programmatically in swift.

我的目标是拥有 meetingFormView 宽度不超过300。使用IB时,我会给宽度约束一个较低的优先级,而给 lessThanOrEqualToConstant一个较高的优先级。但是我无法正常工作。

My goal is to have the meetingFormView no more than 300 wide. Using IB I would give the width constraint a lower priority and give a higher priority to the "lessThanOrEqualToConstant". But I can't get it to work.

我已经尝试过:

meetingFormView.translatesAutoresizingMaskIntoConstraints = false

let constraintWidth = NSLayoutConstraint(
        item: meetingFormView,
        attribute: NSLayoutAttribute.width,
        relatedBy: NSLayoutRelation.equal,
        toItem: startView,
        attribute: NSLayoutAttribute.width,
        multiplier: 1,
        constant: 0)
constraintWidth.priority = .defaultHigh

NSLayoutConstraint.activate([
    meetingFormView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 20),
    meetingFormView.heightAnchor.constraint(equalToConstant: 170),
    meetingFormView.widthAnchor.constraint(lessThanOrEqualToConstant: 300),
    meetingFormView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
    constraintWidth
])

感谢任何帮助

推荐答案

实际上似乎需要行代码来在代码中设置优先的基于锚定约束:

It actually seems to take three lines of code to set up a prioritized "anchor-based" constraint in code:

let widthConstraint = meetingFormView.widthAnchor.constraint(equalToConstant: 170)
widthConstraint.priority = UILayoutPriority(rawValue: 500)
widthConstraint.isActive = true

好像我尝试设置 let 的> isActive 声明Xcode(也许是Swift?)无法识别类型为 NSLayoutConstraint 。并且使用 UILayoutPriority(rawValue:)似乎是设置优先级的最佳方法(唯一?)。

It seems like if I try to set isActive with the let declare Xcode (maybe Swift?) doesn't recognize that the type is NSLayoutConstraint. And using UILayoutPriority(rawValue:) seems to be the best (only?) way to set priorities.

这个答案与您所做的完全不符,我相信它将与IB一起使用。只需将 let 替换为创建 IBOutlet ,就不需要 isActive 行。

While this answer doesn't conform exactly with what you are doing, I believe it will work with IB. Just replace the let with creating an IBOutlet and there should be no need for the isActive line.

很显然,要在以后的代码中更改优先级,您只需要:

Obviously, to change the priority later in code you just need:

widthConstraint.priority = UILayoutPriority(rawValue: 750)

这篇关于快速设置约束条件的优先级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆