вы должны использовать обычный 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
не стесняйтесь спрашивать, не ясно ли что-нибудь! это результат кстати:
что вы имеете в виду «но это будет работать только тогда, когда UILabel имеет постоянную ширину»? –
@ AndréSlotta, насколько я пробовал до сих пор, я могу объединить два элемента, только если у обоих из них есть ограничения ширины – user3766930