如何使用SnapKit在ScrollView中居中按钮数组

时间:2017-03-07 08:35:34

标签: swift snapkit

如何使用SnapKit在ScrollView中垂直居中下面的按钮数组。

for i in 0..<3 {

        itemCount = i

        let aButton = UIButton(type: .custom)

        aButton.frame = CGRect(x: xCoord, y: yCoord, width: buttonWidth, height: buttonHeight)
        aButton.backgroundColor = UIColor.blue
        aButton.layer.cornerRadius = aButton.frame.size.width / 2
        aButton.clipsToBounds = true

        xCoord += buttonWidth + gapBetweenButtons

        aScrollView.addSubview(aButton)

        aButton.snp.makeConstraints { (make) in
            make.center.equalTo(aScrollView)
        }
    }

1 个答案:

答案 0 :(得分:0)

完成等间距按钮阵列的最佳方法是使用UIStackView。这应该有效:

let buttonStackView = UIStackView()
buttonStackView.axis = .vertical
buttonStackView.distribution = .equalSpacing
for i in 0..<3 {
    itemCount = i

    let aButton = UIButton(type: .custom)

    aButton.frame = CGRect(x: xCoord, y: yCoord, width: buttonWidth, height: buttonHeight)
    aButton.backgroundColor = UIColor.blue
    aButton.layer.cornerRadius = aButton.frame.size.width / 2
    aButton.clipsToBounds = true

    xCoord += buttonWidth + gapBetweenButtons

    buttonStackView.addArrangedSubview(aButton)

}
aScrollView.addSubview(buttonStackView)
buttonStackView.snp.makeConstraints { (make) in
    make.centerY.equalToSuperview()
}