我是新手,我写了一个继承自StackView
的customView,我用几个属性以编程方式创建了一个button
,当我将它添加到我的自定义视图时,我有两个问题:
addArrangedSubview(myBtn)
,我的视图会忽略我添加的属性并填充整个宽度。但如果我使用addSubView(myBtn)
,它没关系(44x44的蓝色方块)addArrangedSubview(myBtn)
时,它完美无缺。这是我的自定义视图类:
addTarget()
这是预览:
myBtn
addSubView(myBtn)
import UIKit
class RatingControl: UIStackView {
//MARK: Initialization
override init(frame: CGRect) {
super.init(frame: frame)
setupButtons()
}
required init(coder: NSCoder) {
super.init(coder:coder)
setupButtons()
}
//MARK: Private Methods
private func setupButtons() {
// Create the button
let button = UIButton()
button.backgroundColor = UIColor.blue
// Add constraints
button.translatesAutoresizingMaskIntoConstraints = false
button.heightAnchor.constraint(equalToConstant: 44.0).isActive = true
button.widthAnchor.constraint(equalToConstant: 44.0).isActive = true
// Setup the button action
button.addTarget(self, action: #selector(ratingButtonTapped(_:)), for: .touchUpInside)
// Add the button to the stack
addArrangedSubview(button)
}
//MARK: Button Action
@objc func ratingButtonTapped(_ sender: Any) {
print("Button pressed 👍")
}
}
和有什么区别?为什么会出现这些问题
我假设您想要水平添加几个按钮(例如使用典型的“星级”评级控件)。
一个,可能从它的addSubView()
方法猜测,根据其addArrangedSubview()
,UIStackView
,.addArrangedSubview()
和.axis
属性,以及它的.alignment
安排其子视图。
所以,做一些关于.distribution
及其如何使用的阅读。最有可能的是,您目前正在限制自定义视图:
因此,将您的按钮添加为.spacing
会导致它延伸到堆栈视图的宽度,因为这是默认值。
将其添加为frame
只需覆盖堆栈视图上的按钮,而不是允许堆栈视图排列它,然后堆栈视图的高度可能为零 - 因此无法轻触按钮。
添加自定义堆栈视图时,请尝试仅设置顶部和前导约束。这应该给你一个可以点击的UIStackView
按钮。
当您使用arrangedSubView
添加更多按钮时,这些按钮将水平排列,这可能是您想要的。