Search code examples
iosswiftuibuttontvos

Swift: Setting the height and width of buttons has no effect


I have this tabBar, created programmatically:
enter image description here

func createTabBar() {
       var arrangedSubviews = [UIView]()
       if let menus = CMSessionManager.sharedInstance.menus {
           for menu_item in menus {
               if let menuInfoDetails = menu_item as? [String: Any] {
                   let tabButton = CustomButton(color: .red, titleString: menuInfoDetails["label"] as! String)
                   // This apparently has no effect on button size
                   tabButton.frame = CGRect(x: 100, y: 100, width: 100, height: 50)
                   arrangedSubviews.append(tabButton)
               }
           }
           stackView.alignment = .leading
           stackView = UIStackView(arrangedSubviews: arrangedSubviews)
           stackView.translatesAutoresizingMaskIntoConstraints = false
           stackView.distribution = .fillProportionally
           stackView.axis = .horizontal
           stackView.spacing = 8
           self.view.addSubview(stackView)
           stackView.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 24).isActive = true
           stackView.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 0).isActive = true
           stackView.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: 0).isActive = true
       }
   }
   

I've been trying to change the buttons sizes programmatically:

tabButton.frame = CGRect(x: 100, y: 100, width: 100, height: 50)

No matter which height or width, or x y position I set, nothing changes.
Any idea what's wrong?


Solution

  • Instead of setting a frame directly, use AutoLayout (constraints):

    NSLayoutConstraint.activate([
        tabButton.heightAnchor.constraint(equalToConstant: 100),
        tabButton.widthAnchor.constraint(equalToConstant: 100)
    ])
    

    Also, since you are using stack view, setting x and y values will have no effect since its the sole stack views job to layout these views in appropriate places. Since you are using spacing in your stack view, there is no point in setting width constraint so you should be good with adjusting this value, and using only height constraint.

    NSLayoutConstraint.activate([
        tabButton.heightAnchor.constraint(equalToConstant: 100)
    ])