Swift 3改变细胞形状和属性

时间:2016-12-06 00:43:31

标签: ios swift uicollectionview

我有一个小程序打印"块"到屏幕。我希望块号8和11是圆圈,但我无法确定如何单独引用它们。

当这段代码运行时(无论我如何设置for循环约束),它将放置与我的items数组中一样多的块。

我以为我可以说一些像计数一样的东西。 8 ....等等,但即使它只运行一次,它也会放置许多物品,而物品和物品会被放置在物品上。到屏幕。无论如何,我希望能够让#8和#11成为圈子。

提前致谢

let reuseIdentifier = "cell"
var items = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18"]

// MARK: - UICollectionViewDataSource protocol

// tell the collection view how many cells to make
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return self.items.count
}

// make a cell for each cell index path
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    // get a reference to our storyboard cell
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! MyCollectionViewCell
    // Use the outlet in our custom class to get a reference to the UILabel in the cell


    for _ in 0..<18 {
    let rnd1 = Double.random(min: 0.1, max: 1.0)
    let rnd2 = Double.random(min: 0.1, max: 1.0)
    let rnd3 = Double.random(min: 0.1, max: 1.0)
    cell.myLabel.text = self.items[indexPath.item]
    cell.backgroundColor = UIColor(red: CGFloat(rnd1), green: CGFloat(rnd2), blue: CGFloat(rnd3), alpha: CGFloat(1.0))
    cell.myLabel.text = self.items[indexPath.item]
    }

    return cell
}

// MARK: - UICollectionViewDelegate protocol

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    // handle tap events
    count += 1
    counterLabel.text = "\(count)"
    print("You selected cell #\(indexPath.item)!")
}

Here's what the code is producing

1 个答案:

答案 0 :(得分:0)

如果您只需要一个视觉圆形单元格,则可以将单元格内UIView的cornerRadius设置为等于宽度和高度。 还包括空闲注释,您无需循环生成单元格。您可以尝试类似于以下的代码:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    // get a reference to our storyboard cell
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! MyCollectionViewCell
    // Use the outlet in our custom class to get a reference to the UILabel in the cell

    let rnd1 = Double.random(min: 0.1, max: 1.0)
    let rnd2 = Double.random(min: 0.1, max: 1.0)
    let rnd3 = Double.random(min: 0.1, max: 1.0)
    cell.myLabel.text = self.items[indexPath.item]
    cell.backgroundColor = UIColor(red: CGFloat(rnd1), green: CGFloat(rnd2), blue: CGFloat(rnd3), alpha: CGFloat(1.0))
    cell.myLabel.text = self.items[indexPath.item]

    if indexPath.item == 7 || indexPath.item == 10 {
        cell.myCustomBackground.layer.cornerRadius = cell.myCustomBackground.frame.width
    }

    return cell
}

myCustomBackground是一个以单元格为中心的Square UIView。 另外,关于识别单元格的问题,在集合视图中,indexPath.item将为您提供在该部分中的位置。