【问题标题】:How do I create an action that changes the properties of a specific uicollectionviewcell?如何创建更改特定 uicollectionviewcell 属性的操作?
【发布时间】:2019-06-20 18:41:10
【问题描述】:

我有一个带有 UICollectionView 的应用程序。每个自定义单元格都有一个圆形进度视图和一个应该加快进度的按钮,但我不知道如何在按钮操作中更改特定单元格子视图的属性。

我试过了

  • 将目标添加到“cellForItemAt indexPath”函数内的按钮,然后如何调用目标函数内的特定单元格。

  • 在自定义单元格类中添加 IBAction,但再次出现同样的问题

基本上问题是如何在“cellForItemAt”函数之外的某个索引路径调用特定单元格?

【问题讨论】:

  • 您不想尝试通过从可见的单元格中获取特定单元格的子视图来更新它。您想要更新单元格确定其进度的基础数据,然后在适当的索引路径处重新加载单元格。

标签: ios xcode uikit swift4 uicollectionviewcell


【解决方案1】:

你可以像这样设置你的 UICollectionViewCell 子类:

class MyCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var button: UIButton!
    @IBOutlet weak var progressView: UIProgressView!

    var buttonAction: (() -> Void)?

    @IBAction func didPressButton() {
        buttonAction?()
    }

}

在你的 UITableViewDelegate 中

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "your identifier", for: indexPath) as! MyCollectionViewCell
    cell.buttonAction = {
        //Do whatever you wish
    }
    ...
    ...
    return cell
}

【讨论】:

  • 这很有意义,但发生了一些奇怪的事情。每当我单击添加按钮时,它就会添加到下面的单元格上,然后在单元格上来回添加。
  • 在闭包中我简单地说 cell.servingsEaten += 1 这是一个营养应用程序 btw 和 self.collectionView.reloadData() 它通过 cell.label.text = "(servingsEaten) 更新标签。 ..”
  • 尝试单独保持单元格的状态,这样当您调用reloadData() 时,您的单元格可以重新配置。例如。您可以在prepareForReuse() 方法中重置您的单元格外观,然后在func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 中相应地重新配置它
【解决方案2】:

cellForItemAt indexPath 函数内为按钮添加目标,同时将索引路径作为标签发送,按钮函数如下:-

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "your identifier", for: indexPath) as! MyCollectionViewCell
        cell.buttonAction = {
            //Do whatever you wish
        }
        ...
        ...
        **cell.button.tag = indexPath.row**
        return cell
    }

然后是您设置为目标的函数,您需要通过编写以下代码更新该特定单元格以更新 UI

[self.collectionView reloadItemsAtIndexPaths:@[Sender.tag]];

【讨论】:

    猜你喜欢
    • 2016-01-22
    • 1970-01-01
    • 2018-02-22
    • 2016-08-02
    • 2012-03-27
    • 1970-01-01
    • 2017-06-13
    • 1970-01-01
    相关资源
    最近更新 更多