在UICollectionViewCell中创建多个UIImageViews

时间:2018-11-19 10:29:53

标签: arrays swift

我试图在一个UIImageView中创建多个UICollectionViewCell,所以我写了这段代码,但显然没有附加到lines上。

class chartsCell: UICollectionViewCell {

    var lines = [UIImageView]()
    var chartValueCount = Int()

    override func prepareForReuse() {
        super.prepareForReuse()
        lines.removeAll()
        chartValueCount = 0
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        for i in 0 ..< chartValueCount {
            let line = UIImageView(frame: CGRect(x: frame.width * CGFloat(i + 1) / CGFloat(chartValueCount + 1) - (10 * CGFloat(i + 1)), y: 0, width: 20, height: frame.height))
            line.backgroundColor = UIColor.blue
            line.layer.masksToBounds = true
            line.layer.cornerRadius = 10
            lines.append(line)
            contentView.addSubview(lines[i])
        }
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

我在这里更改chartValueCount

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "chartsCell", for: indexPath) as! chartsCell
    cell.chartValueCount = chartValueCount[indexPath.row]
    return cell
}

chartValueCount数组中有三个值,当我打印cell.lines时,它会打印三个[]。 由于lines为空,因此CollectionView中没有任何显示。如何正确填充?

1 个答案:

答案 0 :(得分:1)

chartCell类:UICollectionViewCell {

var lines = [UIImageView]()
var chartValueCount:Int{
    didSet{
        for i in 0 ..< chartValueCount {
            let line = UIImageView(frame: CGRect(x: frame.width * CGFloat(i + 1) / CGFloat(chartValueCount + 1) - (10 * CGFloat(i + 1)), y: 0, width: 20, height: frame.height))
            line.backgroundColor = UIColor.blue
            line.layer.masksToBounds = true
            line.layer.cornerRadius = 10
            lines.append(line)
            contentView.addSubview(lines[i])
        }
    }
}

override func prepareForReuse() {
    super.prepareForReuse()
    lines.removeAll()
    chartValueCount = 0
}

override init(frame: CGRect) {
    super.init(frame: frame)

}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

}