Swift UIStackView utilize full width of UIStackView

Deepak picture Deepak · Mar 16, 2018 · Viewed 8.2k times · Source

In above screen, you can see I am using a UIStackView to fill radio buttons vertically. problem is my radio buttons not utilising the full width of UIStackView when I use stackV.alignment = .leading it shows label as "dis..lified" instead of disqualified.

UISTackView Code

let ratingStackView : UIStackView = {

    let stackV = UIStackView()
    stackV.translatesAutoresizingMaskIntoConstraints = false
    stackV.backgroundColor = UIColor.yellow
    stackV.axis = .vertical
    stackV.distribution = .fillEqually
    stackV.alignment = .leading
    return stackV
}()

Layout of UIStackView

func setupView(){
    view.addSubview(ratingStackView)

    ratingStackView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true

    ratingStackView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor,constant: 8).isActive = true

    ratingStackView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor).isActive = true

    ratingStackView.heightAnchor.constraint(equalToConstant: 200).isActive = true

    //Add radio buttons to stackview
    for ratingButton in ratingRadioButtons{
        ratingStackView.addArrangedSubview(ratingButton)
    }        
}

what property I need to set to utilize full width can you please tell I am new to the Swift for radio buttons. I am using DLRadioButton.

Answer

PGDev picture PGDev · Mar 18, 2018

To get this working, you need to make following changes in the layout:

1. Set UIStackView's alignment property to fill, i.e.

stackV.alignment = .fill

2. Set UIButton's Horizontal Alignment to left wherever you are creating the RadioButton either in .xib file or through code.

In .xib, you can find the property in interface here:

enter image description here

if you are creating the button using code, use the following line of code:

ratingButton.contentHorizontalAlignment = .left

Let me know if you still face the issue. Happy coding..🙂