【问题标题】:How to get cell atIndex in UICollectionView with swift?如何快速获取 UICollectionView 中的单元格 atIndex?
【发布时间】:2015-05-22 20:55:02
【问题描述】:

我正在以编程方式制作集合视图。 这是 viewDidLoad func 中的代码

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

【问题讨论】:

    标签: ios swift uicollectionview


    【解决方案1】:

    这是在给定 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 更新了动作函数

    @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
            }
        }
    }
    

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

    【讨论】:

    • 完美!谢谢!
    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      适用于 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"
      }  
      

      【讨论】:

        【解决方案4】:

        试试 cell.selected 然后改变颜色

        【讨论】:

          【解决方案5】:

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

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

          【讨论】:

          • 此代码用于 UITableView,而不是像提问者想要的那样用于 UICollectionView。
          猜你喜欢
          • 2015-08-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多