Home > Enterprise >  Why doesn't my subview fill the view in UIKit?
Why doesn't my subview fill the view in UIKit?

Time:09-27

I'm doing a project in UIKit (XCode) for school: "Four In A Row" game. I need to create a square grid in my view with custom items inside (1 vertical stack with N horizontal stacks containing N buttons). So, the light blue square is a UIView I added to the superview, it's called "squareView". I'm trying to insert a UIStackView programmatically to the squareView. It works, almost, because I need the stack to fill the entire squareView and as you can see it doesn't take the entire accessible space. How can I solve this?enter image description here

CodePudding user response:

When the bounds change for a view controller's view, the view adjusts the positions of its subviews and then the system calls the viewDidLayoutSubviews method. So you need to set StackView's frame in viewDidLayoutSubviews so you will get updated bounds of the squareView view. Now to do this you need a reference of StackView, so declare one optional property and initialise it createGrid function.

var verticalStack: UIStackView?

func createGrid(){
    let verticalStack = UIStackView()        
    verticalStack.frame = squareView.bounds
    verticalStack.backgroundColor=.systemRed
    verticalStack.axis = •horizontal
    verticalStack.distribution=.fillEqually
    verticalStack.spacing = 0
    squareView.addSubview(verticalStack)
    self.verticalStack = verticalStack //Set reference
}

//Set frame in viewDidLayoutSubviews
override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    self.verticalStack?.frame = squareView.bounds
}
 
  • Related