Swift:StackView中的单选按钮无法正确显示

时间:2018-09-01 19:22:49

标签: ios swift stackview

我在stackView中创建了一个单选按钮列表,但我不明白为什么它们显示不正确,它们未正确对齐

我希望我的所有按钮都在左侧正确对齐,因为我可以解决此问题,谢谢! And here is the result in photo:

这是代码的一部分:

var buttons = [UIButton]()
var titles = ["Lasy", "What I've been told", "I'm do into it", "Close the best i can", "Hard core"]


func setupUI() {

    for title in titles {
        // create button
        let button = UIButton(type: .custom)
        button.setTitleColor(.black, for: .normal)
        button.setTitle(title, for: .normal)
        button.setImage(UIImage(named: "uncheck.png")!, for: .normal)

        // if the selected button cannot be reclick again, you can use .Disabled state
        button.setImage(UIImage(named: "check.png")!, for: .selected)
        button.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 35)
        button.addTarget(self, action: #selector(radioButtonAction), for: .touchUpInside)

        buttons.append(button)
    }

    for button in buttons {
        addArrangedSubview(button)
    }

    setupUserChoice()
}

func setupUserChoice(){
    if titles.contains(value) {
        let valueIndex = titles.index(of: value)

        radioButtonAction(sender: buttons[valueIndex!])
    }
}

func setStackView() {
    stackView.translatesAutoresizingMaskIntoConstraints = false
    stackView.axis = .vertical
    stackView.distribution = .fill
    stackView.spacing = 16.0
    stackView.alignment = .leading
}

2 个答案:

答案 0 :(得分:1)

问题与您尝试设置 imageEdgeInsets 的方式有关。它仅调整图像位置,而不相应地增加按钮的大小。要增加按钮的大小,您需要设置 contentEdgeInsets 。但是,您还需要根据图像位置的变化来调整标题位置。您可以为此使用 titleEdgeInsets

因此,删除您的代码button.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 35),然后将其替换为:-

let leftPadding_beforeImage: CGFloat = 35
let gapBetweenImageAndTitle: CGFloat = 8
let rightPadding_afterTitle: CGFloat = 16

button.imageEdgeInsets = UIEdgeInsetsMake(0, leftPadding_beforeImage, 0, 0)
button.titleEdgeInsets = UIEdgeInsetsMake(0, (leftPadding_beforeImage+gapBetweenImageAndTitle), 0, -(leftPadding_beforeImage+gapBetweenImageAndTitle))
button.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, (leftPadding_beforeImage+gapBetweenImageAndTitle+rightPadding_afterTitle))

我希望变量名是不言自明的。如果您想了解有关UIButton edgeInsets的更多信息,建议您阅读this fantastic answer

答案 1 :(得分:0)

设置每个按钮的框架,因为UIStackView使用固有内容大小。例如:

button.frame = CGRect(x: 0, y: 0, width: 100, height: 20)