如何使用swift在UICollectionView中获取单元格atIndex?

cbeh67ev  于 2023-03-22  发布在  Swift
关注(0)|答案(6)|浏览(160)

我正在以编程方式创建集合视图。

let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    layout.sectionInset = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)
    layout.itemSize = CGSize(width: 90, height: 120)
    collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
    collectionView!.dataSource = self
    collectionView!.delegate = self
    collectionView!.registerClass(CollectionViewCell.self, forCellWithReuseIdentifier: "CollectionViewCell")
    collectionView!.layer.cornerRadius = 2
    collectionView!.backgroundColor = UIColor.redColor()
    self.containerView.addSubview(collectionView!)

这些是我的集合视图函数

func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
    return 1
}

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 8
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionViewCell", forIndexPath: indexPath) as! CollectionViewCell
    cell.backgroundColor = UIColor.blackColor()
    cell.buttonView.addTarget(self, action: Selector("Action\(indexPath.row):"), forControlEvents: UIControlEvents.TouchUpInside)
    return cell
}

想法是我在单元格中有一个按钮,当我按下它时,单元格应该改变颜色,这是动作函数

func Action0(sender: UIButton!) {
    var indexPath = NSIndexPath(forRow: 0, inSection: 0)
    let cell = collectionView!.dequeueReusableCellWithReuseIdentifier("CollectionViewCell", forIndexPath: indexPath ) as! CollectionViewCell
    cell.backgroundColor = UIColor.blueColor()

这是collectionViewCell类

class CollectionViewCell: UICollectionViewCell {

required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}

var buttonView: UIButton!
override init(frame: CGRect) {
    super.init(frame: frame)

    buttonView = UIButton.buttonWithType(UIButtonType.System) as! UIButton
    buttonView.frame = CGRect(x: 0, y: 16, width: frame.size.width, height: frame.size.height*2/3)

    contentView.addSubview(buttonView)
}

}
按钮和动作都正常,但单元格不变色,我猜问题出在这一行

let cell = collectionView!.dequeueReusableCellWithReuseIdentifier("CollectionViewCell", forIndexPath: indexPath ) as! CollectionViewCell
fhg3lkii

fhg3lkii1#

这是获取给定indexPath处的单元格的方法:

let cell = collectionView!.cellForItemAtIndexPath(indexPath)

但是,您也可以尝试:

cell.contentView.backgroundColor = UIColor.blueColor()

注:

虽然上面的方法可能有效,但我想鼓励你尝试不同的实现来实现相同的功能。你的实现将需要你为每个CollectionViewCell都有一个单独的Action#函数,以及在每个方法中手动创建indexPath,而你可能只有一个!

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionViewCell", forIndexPath: indexPath) as! CollectionViewCell
    cell.backgroundColor = UIColor.blackColor()
    cell.buttonView.addTarget(self, action: Selector("action"), forControlEvents: UIControlEvents.TouchUpInside)
    return cell
}

这个方法的函数应该是这样的:

func action(sender: UIButton!) {
    var point : CGPoint = sender.convertPoint(CGPointZero, toView:collectionView)
    var indexPath = collectionView!.indexPathForItemAtPoint(point)
    let cell = collectionView!.cellForItemAtIndexPath(indexPath)
    cell.backgroundColor = UIColor.blueColor()
}

Swift 4.2更新了action函数

@objc func action(sender: Any){
    print("tickedOffPressed !")
    if let button = sender as? UIButton {
        let point: CGPoint = button.convert(.zero, to: collectionView)
        if let indexPath = collectionView!.indexPathForItem(at: point) {
            let cell = collectionView!.cellForItem(at: indexPath)
            cell?.backgroundColor = UIColor.blue
        }
    }
}

只是一个建议!编码快乐!:)

nnsrf1az

nnsrf1az2#

Swift 4中可以通过以下方式获取CollectionView的单元格:

let indexPath = IndexPath(item: 3, section: 0);  
if let cell = myCollectionView .cellForItem(at: indexPath)  
{   
   // do stuff...  
}
pgx2nnw8

pgx2nnw83#

适用于Swift 5.5和iOS 15

Lakhdeep Singh答案的基础上,如果你想访问某个单元格的属性,你需要将它转换为你想要的单元格(例如CustomCell)。例如,如果这个CustomCell有一个nameLabel,你可以这样访问它:

let indexPath = IndexPath(item: 3, section: 0);  
if let customCell = myCollectionView .cellForItem(at: indexPath) as? CustomCell {   
    customCell.nameLabel.text = "some text"
}
rsaldnfx

rsaldnfx4#

尝试单元格.选定,然后更改颜色

fslejnso

fslejnso5#

如果单元格存在于视图中,则第一个条件将匹配,否则将调用

let indexPath = IndexPath(item: 0, section: 0);  
    if let customCell = myCollectionView.cellForItem(at: indexPath) as? CustomCell {   
        customCell.nameLabel.text = "some text"
    }else {
    if let customCell = myCollectionView.dequeueReusableCellWithReuseIdentifier("CustomCell", forIndexPath: indexPath) as? CustomCell {
        customCell.nameLabel.text = "some text"
    }
f2uvfpb9

f2uvfpb96#

在Swift 2中,你可以通过以下方式获取行:

let point : CGPoint = sender.convertPoint(CGPointZero, toView:myTableView)
let indexPath = myTableView.indexPathForRowAtPoint(point)
let cell = myTableView.cellForRowAtIndexPath(indexPath!)

相关问题