Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set NSButton size in NSStackView

Tags:

swift

cocoa

I programmatically create buttons using this code

 let button: NSButton = NSButton()
 button.action = #selector(ViewController.eject)
 button.bezelStyle = .texturedSquare                              
 buttons.append(button)
 stackView.addView(buttons[i], in: .leading)
             

The problem is that those buttons appear like that enter image description here

I would like to set the (x , y) position and the size of those buttons. For example, I would like to set their width to fill the whole space. I tried multiple solutions:

button.frame = CGRect(x: 0.0,y: 0.0,width: 100.0,height: 100.0)

and play with the arguments, but still their size don't change. I then tried to add them as SubViews to stackView, but obviously they overlap with each other. Any suggestion?

like image 366
Jacopo Avatar asked Sep 24 '26 12:09

Jacopo


1 Answers

To fix those buttons you first have to modify the StackView element in the storyboard. Go to the menu of the storyboard and modify it like that enter image description here

With the "fill" distribution you let the buttons to fill the entire width of the stackview. With "spacing" you define how much space there has to be between each button.

Then you go there

enter image description here

To give some space to the buttons just play with the Edge Insets values. Then set the horizontal Hugging Propriety to 250.

The last thing you have to do is to add this code in your ViewController file.

button.setContentHuggingPriority(NSLayoutConstraint.Priority.init(1), for: .horizontal)
button.translatesAutoresizingMaskIntoConstraints = false

In this way you'll the the horizontal Hugging Propriety of the button to 1.
Here's the buttons I created

enter image description here

like image 132
Jacopo Avatar answered Sep 27 '26 02:09

Jacopo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!