我试图在一个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中没有任何显示。如何正确填充?
答案 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")
}
}