arrays - 在 UICollectionViewCell 中创建多个 UIImageView

标签 arrays swift

我试图在 UICollectionViewCell 中制作多个 UIImageView,所以我写了这段代码,但显然没有任何内容附加到 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 时,它会打印三个 []。 CollectionView 中没有显示任何内容,因为 lines 是空的。如何正确填写?

最佳答案

类 chartsCell: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")
}

关于arrays - 在 UICollectionViewCell 中创建多个 UIImageView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53372638/

相关文章:

从另外两个数组创建一个静态分配的数组

javascript - 用其他 Array 元素填充每个 null 元素

java - 数组中需要 = new String[] 吗?

ios - 如何移动 UIView 并使用 Swift 以编程方式放置新的 UIView?

swift - XCTest 输出显示错误但没有抛出错误

php根据其他数组的顺序重新排序数组

php - 从特定数字重新索引数组

ios - ObjectMapper - 嵌套动态键

ios - 在 MKMapView 中计算方位在穿过 180 度子午线时给出错误值

swift - 使用未声明的类型 PNObjectEventListener