D
D
Darkness2020-09-27 02:21:24
Swift
Darkness, 2020-09-27 02:21:24

What am I doing wrong when creating a UIStackView programmatically?

Goal:
Create something like this, programmatically:
5f6fcbbbd736e072859771.png

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")
    }
}


Then I call in the controller I need:
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)
        ])
    }


This is what debugUI looks like:
5f6fcc9da017e181460714.png

Question:
What did I do wrong? There are no errors or warnings. I just don't see the UIView that I created and pushed into the UIStackView.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Snak59, 2020-09-27
@AntonBrock

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.
5f7033d8b127f945222440.png

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question