您需要使用将该@objc
属性与didTapCommentButton(_:)
一起使用#selector
。
您说您这样做了,但又遇到另一个错误。我的猜测是,新错误是Post
与Objective-C不兼容的类型。仅当方法的所有参数类型及其返回类型均与Objective-C兼容时,才可以将方法公开给Objective-C。
您可以通过创建Post
的子类来解决此问题NSObject
,但这并不重要,因为to的参数无论如何didTapCommentButton(_:)
都不会Post
。动作函数的参数是动作的发送者,而该发送者将是commentButton
,大概是a UIButton
。您应该这样声明didTapCommentButton
:
@objc func didTapCommentButton(sender: UIButton) {
// ...
}
然后,您将面临获取Post
与所点击按钮相对应的问题。有多种获取方法。这是一个
我收集到(因为您的代码说了cell.commentButton
),您正在设置一个表视图(或一个集合视图)。并且由于您的单元格具有一个名为的非标准属性commentButton
,因此我假设它是一个自定义UITableViewCell
子类。因此,假设您的单元格是这样PostCell
声明的:
class PostCell: UITableViewCell {
@IBOutlet var commentButton: UIButton?
var post: Post?
// other stuff...
}
然后,您可以从按钮开始沿视图层次结构查找PostCell
,并从中获取帖子:
@objc func didTapCommentButton(sender: UIButton) {
var ancestor = sender.superview
while ancestor != nil && !(ancestor! is PostCell) {
ancestor = view.superview
}
guard let cell = ancestor as? PostCell,
post = cell.post
else { return }
// Do something with post here
}