[英]how can I center two elements (without knowing their width) next to each other in Swift?
剛開始我考慮過UILayoutGuides,但是只要您願意編寫一些東西,它就比這容易得多。 使用UILayoutAnchors,centerX和乘數:
myLabel.centerXAnchor.constraint(equalTo: myView.centerXAnchor, multiplier: 0.33)
myButton.centerXAnchor.constraint(equalTo: myView.centerXAnchor, multiplier: 0.667)
當然,您需要布置的空間不止於此(尤其是垂直位置),是的,您可以使用UILayoutGuides獲得相等的間距 。 但是,只要您正在使用自動布局,並且了解如何為您需要以這種方式編寫代碼的東西設置IBOutlets,就可以使用。
順便說一句,您可以確切地說,就像參考代碼中的超級視圖以使其完美居中一樣。)
您應該使用常規的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
隨時詢問是否不清楚! 結果是順便說一句:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.