Я пытаюсь создать UIStackView
с некоторыми UIButton
.
У меня есть массив строк, которые содержат текст кнопки.Я пытался отобразить этот массив, создавая массив кнопок.
Тогда я мог бы использовать forEach
для этого массива, чтобы добавить arrangedSubView
.
В настоящее время я вижу только 1кнопка, я подозреваю, что моя кнопка перезаписывается на каждом шаге цикла.
fileprivate var button: UIButton {
let button = UIButton(type: UIButton.ButtonType.system)
return button
}
fileprivate let buttonGroupStackView: UIStackView = {
let stackView = UIStackView()
stackView.axis = .vertical
stackView.distribution = .equalSpacing
return stackView
}()
fileprivate func setupSubViews(_ origin: ChatResponseOrigin) {
let margins = contentView.layoutMarginsGuide
[messageAvatar, buttonGroupStackView].forEach { v in contentView.addSubview(v) }
messageAvatar.image = #imageLiteral(resourceName: "user-avatar")
messageAvatar.anchor(
top: margins.topAnchor, leading: margins.leadingAnchor, size: CGSize(width: 35, height: 35)
)
guard let buttonGroupContent = content?.buttonGroup else { return }
let buttonGroup = buttonGroupContent.map { (b) -> UIButton in
let btn = button
btn.frame = CGRect(x: 0, y: 0, width: 200, height: 40)
btn.backgroundColor = UIColor.blue
btn.setTitle(b.buttonText, for: .normal)
return btn
}
buttonGroup.forEach { b in buttonGroupStackView.addSubview(b) }
buttonGroupStackView.anchor(top: margins.topAnchor, leading: margins.leadingAnchor, trailing: margins.trailingAnchor, size: CGSize(width: 0, height: 400))
}
У меня есть расширение на UIView
, которое я использую для обработки автоматического макета
@discardableResult
func anchor(top: NSLayoutYAxisAnchor? = nil, leading: NSLayoutXAxisAnchor? = nil, bottom: NSLayoutYAxisAnchor? = nil, trailing: NSLayoutXAxisAnchor? = nil, padding: UIEdgeInsets = .zero, size: CGSize = .zero) -> AnchoredConstraints {
translatesAutoresizingMaskIntoConstraints = false
var anchoredConstraints = AnchoredConstraints()
if let top = top {
anchoredConstraints.top = topAnchor.constraint(equalTo: top, constant: padding.top)
}
if let leading = leading {
anchoredConstraints.leading = leadingAnchor.constraint(equalTo: leading, constant: padding.left)
}
if let bottom = bottom {
anchoredConstraints.bottom = bottomAnchor.constraint(equalTo: bottom, constant: -padding.bottom)
}
if let trailing = trailing {
anchoredConstraints.trailing = trailingAnchor.constraint(equalTo: trailing, constant: -padding.right)
}
if size.width != 0 {
anchoredConstraints.width = widthAnchor.constraint(equalToConstant: size.width)
}
if size.height != 0 {
anchoredConstraints.height = heightAnchor.constraint(equalToConstant: size.height)
}
[anchoredConstraints.top, anchoredConstraints.leading, anchoredConstraints.bottom, anchoredConstraints.trailing, anchoredConstraints.width, anchoredConstraints.height].forEach { $0?.isActive = true }
return anchoredConstraints
}