我正在尝试以编程方式布置StackView,我想实现的效果是
swift - UIStackView扩展 subview 以使其对齐-LMLPHP

但相反,我越来越

swift - UIStackView扩展 subview 以使其对齐-LMLPHP

我不明白为什么loadingDotView正在拉伸以填充所有空间?

   let loadingDotView: UIView = {
        let ldv = UIView()
        ldv.backgroundColor = .white
        ldv.alpha = 0
        ldv.frame = CGRect(x: 0, y: 0, width: 20, height: 20)
        ldv.layer.cornerRadius = 10
        ldv.layer.masksToBounds = true
        ldv.translatesAutoresizingMaskIntoConstraints = false
        return ldv
    }()

    let dotsStackView: UIStackView = {
        let stackView = UIStackView()
        stackView.axis = .horizontal
        stackView.distribution = .equalSpacing
        stackView.translatesAutoresizingMaskIntoConstraints = false
        return stackView
    }()


设置代码...

   view.addSubview(dotsStackView)



    NSLayoutConstraint.activate([
            dotsStackView.heightAnchor.constraint(equalToConstant: 20),
            dotsStackView.widthAnchor.constraint(equalToConstant: 100),
            dotsStackView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            dotsStackView.centerYAnchor.constraint(equalTo: view.centerYAnchor)
        ])



    dotsStackView.addArrangedSubview(loadingDotView)
    dotsStackView.addArrangedSubview(loadingDotView)
    dotsStackView.addArrangedSubview(loadingDotView)

最佳答案

这个(关闭)

let loadingDotView: UIView = {
    let ldv = UIView()
    ldv.backgroundColor = .white
    ldv.alpha = 0
    ldv.frame = CGRect(x: 0, y: 0, width: 20, height: 20)
    ldv.layer.cornerRadius = 10
    ldv.layer.masksToBounds = true
    ldv.translatesAutoresizingMaskIntoConstraints = false
    return ldv
}()


每次访问都返回相同的对象,因此只有一个出现,使它(计算属性)每次访问都创建一个新对象

var loadingDotView: UIView {
    let ldv = UIView()
    ldv.backgroundColor = .white
    ldv.alpha = 0
    ldv.frame = CGRect(x: 0, y: 0, width: 20, height: 20)
    ldv.layer.cornerRadius = 10
    ldv.layer.masksToBounds = true
    ldv.translatesAutoresizingMaskIntoConstraints = false
    return ldv
}


并添加

stackView.spacing = 20
stackView.distribution = .fillEqually


swift - UIStackView扩展 subview 以使其对齐-LMLPHP

关于swift - UIStackView扩展 subview 以使其对齐,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53592848/

10-10 17:15