web-dev-qa-db-ja.com

swift

私はSwiftでプログラム的に制約が機能するように優先するのに苦労してきました。

私の目標は、meetingFormViewの幅を300以下にすることです。 IBを使用すると、幅の制約に低い優先度を与え、「lessThanOrEqualToConstant」に高い優先度を与えます。しかし、私はそれを機能させることができません。

私はこれを試しました:

        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
        ])

どんな助けでも大歓迎です

4
Torsten Nielsen

コードに優先順位の付いた「アンカーベース」の制約を設定するには、実際にはthree行のコードが必要なようです。

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

isActivelet宣言で設定しようとすると、Xcode(おそらくSwift?)はタイプがNSLayoutConstraintであることを認識しないようです。そして、UILayoutPriority(rawValue:)を使用することが、優先順位を設定するための最良の(唯一の?)方法のようです。

この答えはあなたがしていることに正確に適合していませんが、私はそれがIBでうまくいくと信じています。 letIBOutletの作成に置き換えるだけで、isActive行は必要ありません。

明らかに、change後のコードの優先順位に必要なのは:

_widthConstraint.priority = UILayoutPriority(rawValue: 750)
_
14
dfd