2017-01-11 7 views
0

私のswiftアプリで私はUILabelとUIButtonのビューを持っています。ストーリーボードでは、次のようになります。スウィフトで2つの要素を隣り合わせに配置するにはどうすればいいですか?

enter image description here

は、私はグループそして、これら二つの要素と、そのグループに制約を置くことができます知っているが、UILabelは一定の幅を持っているときにのみ動作します。

私はこのように、このグループを表示する:

|  label X  | 

か - ラベルはこのように、長い:私はその効果を得るために制約を適用する必要がありますどのように

| longerlabel X | 

+0

あなたは「UILabelは一定の幅を持っているとき、それがのみ機能します」によって何を意味:これはところで結果ですか? –

+0

@AndréSlotta私が今まで試した限り、2つの要素をグループ化するには、両方に「幅」の制約がある場合のみ – user3766930

答えて

0

最初に私はUILayoutGuidesを検討し、それは限り、あなたはいくつかのことをコーディングすることを喜んでいるように、それよりもはるかに簡単です。 UILayoutAnchors、centerX、および乗算器を使用します。もちろん、

myLabel.centerXAnchor.constraint(equalTo: myView.centerXAnchor, multiplier: 0.33)  
myButton.centerXAnchor.constraint(equalTo: myView.centerXAnchor, multiplier: 0.667) 

を、あなたは(特に垂直位置)これ以上をレイアウトする必要があるとはい、あなたはequal spacingためUILayoutGuidesを使用することができます。しかし、自動レイアウトを使用し、その方法でコーディングする必要があるものに対してIBOutletを設定する方法を理解している限り、これは機能します。

ところで、あなたは、コード内のスーパーは完全にそれを中心を基準のように、正確なことができます。)

0

あなたはコンテナとして定期的UIViewを使用する必要があります。次のようなコードでビューを設定できます。

// configure the content 
let labelText = "Label" 
let buttonTitle = "X" 

// setup the views 
let label = UILabel() 
label.translatesAutoresizingMaskIntoConstraints = false 
label.text = labelText 

let button = UIButton(type: .system) 
button.translatesAutoresizingMaskIntoConstraints = false 
button.setTitle(buttonTitle, for: .normal) 
button.setContentCompressionResistancePriority(label.contentCompressionResistancePriority(for: .horizontal) + 1, for: .horizontal) 

let container = UIView() 
container.translatesAutoresizingMaskIntoConstraints = false 
container.layer.borderColor = UIColor.lightGray.cgColor 
container.layer.borderWidth = 1 

// add the views 
container.addSubview(label) 
container.addSubview(button) 
view.addSubview(container) 

// create the container constraints 
NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "|[lbl]-[btn]|", options: [.alignAllTop, .alignAllBottom], metrics: nil, views: ["lbl": label, "btn": button])) 
NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "V:|[btn]|", options: [], metrics: nil, views: ["btn": button])) 

// center the container 
NSLayoutConstraint(item: container, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1, constant: 0).isActive = true 
NSLayoutConstraint(item: container, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 1, constant: 0).isActive = true 

// make sure the container does not extend the view's width 
NSLayoutConstraint(item: container, attribute: .leading, relatedBy: .greaterThanOrEqual, toItem: view, attribute: .leading, multiplier: 1, constant: 20).isActive = true 

不明な点があればお気軽にお問い合わせください。

enter image description here

関連する問題