I'm newbie and I've wrote a customView inherited from StackView
and I created a button
programmatically with few attributes and when I add it to my custom view, I have two problems:
- If I use
addArrangedSubview(myBtn)
, my view ignores attributes that I added and fills the whole width. But if I useaddSubView(myBtn)
, It's ok(a blue square in 44x44) - If I use
addArrangedSubview(myBtn)
,addTarget()
not works andmyBtn
is not clickable, but when I useaddSubView(myBtn)
, It works perfectly.
Here is my custom view class:
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 π")
}
}
Here is the preview:
What's difference between addSubView()
and addArrangedSubview()
? why these problems happens?
addArrangedSubview
β Plunger