一起添加多个UI元素和约束

时间:2018-10-19 00:22:37

标签: swift autolayout snapkit

我有这样的UIView设置

  • UIView
    • UIScrollView(self.scrollView
      • UIView(self.contentView
      • LineChartView(self.chart
      • M13CheckBox [UIControl的子集]

图表显示包括多条线,我打算通过多个复选框进行控制。但是,我似乎无法将复选框相互限制!

这是我的代码:

    var unconstrainedChecks = [M13Checkbox]()
    for year in years { // years = ["2015","2016","2017"]
        let checkbox = CustomizedCheckBox().checkbox
        checkbox.backgroundColor = .purple
        self.contentView.addSubview(checkbox)
        unconstrainedChecks.append(checkbox)
    }
    for i in 0..<unconstrainedChecks.count - 1 {
        print(i)
        let checkbox = unconstrainedChecks[i]
        let nextCheckbox = unconstrainedChecks[i+1]
        checkbox.snp.makeConstraints { (make) in
            if i == 0 {
                make.top.equalTo(self.chart.snp.bottom).offset(20)
                make.width.height.equalTo(50)
                make.left.equalTo(self.contentView)
            }
            make.bottom.equalTo(nextCheckbox.snp.top)
        }

        nextCheckbox.snp.makeConstraints { (make) in
            make.width.height.equalTo(50)
            make.left.equalTo(self.contentView)
            make.top.equalTo(checkbox.snp.bottom)
        }

    }

CustomizedCheckBox

class CustomizedCheckBox {
    let checkbox: M13Checkbox
    init() {
        checkbox = M13Checkbox()
        checkbox.setCheckState(.checked, animated: false)
        checkbox.stateChangeAnimation = .bounce(.fill)
        checkbox.secondaryTintColor =  UIColor(hexString: "47cae8")
        checkbox.secondaryCheckmarkTintColor = .white //checkmark
        checkbox.tintColor = UIColor(hexString: "53cce7")
    }
}

我看着“查看层次结构”,但根本看不到该复选框。

1 个答案:

答案 0 :(得分:0)

我解决了这个问题。我需要将最后一个复选框限制为self.contentView.bottom

将其添加到nextCheckbox循环中。

            if i + 1 == unconstrainedChecks.count - 1 {
                make.bottom.equalTo(self.contentView.snp.bottom)
            }