I'm trying to create a UIStackView
with some UIButton
's.
I have a an array of Strings that contain the button text. I Was trying to map over that array, creating an array of buttons.
Then I could use forEach
on that array to add arrangedSubView
's.
Currently I only see 1 button, I suspect my button is being overwritten at each step of the loop.
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))
}
I have an extension on my UIView
that I use to handle auto layout
@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
}