简体   繁体   中英

Swift UIStackView utilize full width of UIStackView

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 .

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

1. Set UIStackView's alignment property to fill , ie

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:

在此输入图像描述

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..🙂

Leave alignment with its default value, ie .fill – this stretches arranged views in a direction perpendicular to the stack's axis.

Actually, I suspect that if you are using .leading alignment and do not specify widths of nested controls you are getting auto layout warnings during runtime (could be checked in Visual Debugger in Xcode).

Try proportional distribution.

One more thing to try...Reduce the content hugging priority of the labels.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM