ios - 将方法委托(delegate)给 UItableViewCell Swift

标签 ios swift uitableview delegates

我有一个 UItableView 形式的社交网络订阅源,它有一个单元格。现在,每个单元格都有一个图像,当偶数被触发时,该图像就会动画化。现在,此事件采用字符串形式,将在每个单元格处触发。事件的选项在另一个类(NSObject 类型)中定义。

我的问题: 我在 TableView 中构造了一个协议(protocol)委托(delegate)方法,每当每个单元格触发事件时都会调用该方法。然后,我在 UITableViewCell 类中定义此函数,因为我的图像将在其上设置动画。 一切正常,但我无法弄清楚如何将 TableView 类的委托(delegate)分配给单元格类。我的意思是,如何在 cellView 类中使用 UITableView.delegate = self。我试过使用静态变量,但它不起作用。

我已经研究协议(protocol)一段时间了,但真的无法找到解决方案。

我希望我是清楚的。如果没有,我会在评论中提供一个例子。对不起,这是一个 secret 项目,我不能透露所有细节。

最佳答案

如果我没理解错的话,你是想让你的每个单元格都符合属于它们的 UITableView 的协议(protocol)?如果是这种情况,则无法完成此操作。委托(delegate)设计模式是一对一的关系,即只有一个 UITableViewCells 能够符合 UITableView 的委托(delegate)。

Delegation is a simple and powerful pattern in which one object in a program acts on behalf of, or in coordination with, another object. The delegating object keeps a reference to the other object—the delegate—and at the appropriate time sends a message to it. The message informs the delegate of an event that the delegating object is about to handle or has just handled. The delegate may respond to the message by updating the appearance or state of itself or other objects in the application, and in some cases it can return a value that affects how an impending event is handled. The main value of delegation is that it allows you to easily customize the behavior of several objects in one central object.

引自Apple Docs

我建议您的 UITableViewCell 应该在触发指定事件时调用 block (Objective-C) 或闭包 (Swift) 以实现您正在寻找的目标。在您的 tableView:cellForRowAtIndexPath 函数中设置此闭包。

示例

TableViewController

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
  {
    let cell = tableView.dequeueReusableCell(withIdentifier: "MyTableViewCellID", for: indexPath) as! MyTableViewCell
    cell.eventClosure = {
     //Do something once the event has been triggered.
    }
    return cell
  }

TableViewCell

func eventTriggered()
{
  //Call the closure now we have a triggered event.
  eventClosure()
}

关于ios - 将方法委托(delegate)给 UItableViewCell Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47079135/

相关文章:

ios - 无法在标签中显示经文

适用于应用程序的 iOS 模拟器

iOS 显示警报 Controller 对象

iphone - 从 UITableViewCell 中的详细信息公开按钮显示 UIPopoverController

ios - 为什么 UITableView 为空?

iphone - ios 7 tableView didSelectRowAtIndexPath 在第一次选择时显示空白数据

ios - iTunes Store 操作失败,缺少所需的图标文件

ios - iOS 中来自 JSON 的响应不完整

ios - NSFetchedResultsController 正在删除行而不是在更新核心数据后更新它们

ios - 如何修复 ibtool 因 Main.storyboard 错误 : shouldBeArchived unrecognized 而失败