Answer the question
In order to leave comments, you need to log in
What am I doing wrong when creating a UIStackView programmatically?
Goal:
Create something like this, programmatically:
What I did:
class CHDotsView: UIStackView {
var dotsCount: Int?
init(frame: CGRect = CGRect(x: 0, y: 0, width: 0, height: 0), dotsCount: Int, width: CGFloat, height: CGFloat) {
super.init(frame: frame)
self.axis = .horizontal
self.distribution = .equalSpacing
self.spacing = 20
self.dotsCount = dotsCount
for _ in 1 ... dotsCount {
let dotsView = UIView()
dotsView.backgroundColor = .red
dotsView.layer.cornerRadius = width / 2
dotsView.frame.size.width = width
dotsView.frame.size.height = height
self.addArrangedSubview(dotsView)
}
}
required init(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
func setupDotView() { // данный метод вызывается во ViewDidLoad
let dotsContainer = UIView()
let dots = CHDotsView(dotsCount: 1, width: 10, height: 10)
dotsContainer.addSubview(dots)
dotsContainer.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(dotsContainer)
NSLayoutConstraint.activate([
dotsContainer.widthAnchor.constraint(equalToConstant: 200),
dotsContainer.heightAnchor.constraint(equalToConstant: 100),
dotsContainer.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 120),
dotsContainer.centerXAnchor.constraint(equalTo: self.view.centerXAnchor)
])
}
Answer the question
In order to leave comments, you need to log in
The initializer you are using in the inherited class limits the uistackview to the given frame and does not allow it to resize according to the added dots. It is necessary to create a stack through an empty initializer, but it is not inherited, or I did not find how to do it) If you are not going to extend the stackview functionality, it is better not to use inheritance - in fact, the stack is a container that serves to represent and does not carry additional functionality.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question