以下に、チェックアウトのためのコードをいくつか含めました。私はカスタムUIView
を受け取り、それに別のカスタムサブビューを追加しようとしています。このサブビューは、基本的には同じディメンションで上に横たわるような方法で親ビューに制限する必要があり、親は単にラッパーとして機能します。UIViewのサブビューの自動レイアウト制約をプログラムで設定する
私はNSLayoutConstraint
を使用しようとしましたが、これまでのところ悲惨な失敗をしました。ビューは実際には決して現れません。私は、親ビューと一直線になるべきleft、right、bottom、およびtopの制約を持っています。
私が最初に尋ねるのは、誰かが、以下の方法を使用するときに、自分の論理を説明してください。私が考えたアイテムのパラメータは、(customViewChild
)の制約を設定する実際のビューです。属性は、この制約のために私のの左端を使用したいと言うことです。 relatedBy
は私が間違っている可能性がありますが、まっすぐに見えますが、最後にtoItem
はという自己を指しています。私の子と親の左端を整列させたいと言っているのは.left
です。この論理に欠陥があるのですか、他の何か間違っていますか?
NSLayoutConstraint(item: customViewChild!,
attribute: .left,
relatedBy: .equal,
toItem: self,
attribute: .left,
multiplier: 1.0,
constant: 0.0)
私は、次の例は非常に簡単にIBで行うことができるが、私はNSLayoutConstraint
を理解しようとしていますので、それについての答えを提供してください知っています。最後に、誰かが実際にこのコードを修正して、私が実際の例を持っていれば、それはすばらしいでしょう。
class CustomViewParent: UIView {
var customViewChild: UIView?
override init(frame: CGRect) {
super.init(frame: frame)
setConstraints()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setConstraints()
}
func setConstraints() {
customViewChild = UIView()
addSubview(customViewChild!)
customViewChild?.translatesAutoresizingMaskIntoConstraints = false
let leftConstraint = NSLayoutConstraint(item: customViewChild!,
attribute: .left,
relatedBy: .equal,
toItem: self,
attribute: .left,
multiplier: 1.0,
constant: 0.0).isActive = true
let rightConstraint = NSLayoutConstraint(item: customViewChild!,
attribute: .right,
relatedBy: .equal,
toItem: self,
attribute: .right,
multiplier: 1.0,
constant: 0.0).isActive = true
let topConstraint = NSLayoutConstraint(item: customViewChild!,
attribute: .top,
relatedBy: .equal,
toItem: self,
attribute: .top,
multiplier: 1.0,
constant: 0.0).isActive = true
let bottomConstraint = NSLayoutConstraint(item: customViewChild!,
attribute: .bottom,
relatedBy: .equal,
toItem: self,
attribute: .bottom,
multiplier: 1.0,
constant: 0.0).isActive = true
customViewChild.addConstraint([leftConstraint, rightConstraint, topConstraint, bottomConstraint]);
}
}
'customViewChild.addConstraintを取り除くを見つけることができます。 .. '。 'isActive'をtrueに設定すると、正しいビューに追加されます。 – vacawama
Storyboardまたはnibファイルから 'CustomViewParent'のインスタンスを作成していますか?そうでなければ 'init(coder:)'がおそらく呼び出されていないでしょう。ブレークポイントまたはログを使用して確認します。また、私はあなたが私たちにお勧めします。リーディングと.trailingではなく、レフトとライト。 – Paulw11