的选择您需要使用@objc
属性上didTapCommentButton(_:)
与#selector
使用它。
你说你这样做,但你有另一个错误。我的猜测是,新错误是Post
不是与Objective-C兼容的类型。如果所有参数类型及其返回类型都与Objective-C兼容,则只能将方法公开给Objective-C。
你可以修复,通过使Post
的NSObject
一个子类,但是这不会啦,因为参数didTapCommentButton(_:)
不会是一个Post
反正。动作函数的参数是动作的发件人,并且该发件人将是commentButton
,推测其可能是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
}
FeedViewController的类声明行是什么样的? didTapCommentButton是如何声明的?当您添加@objc时会得到什么错误? – vacawama
更新,我编辑了我的帖子。我远离现在的电脑,所以我忘记了确切的错误信息,但它是XCode告诉我添加它然后在其自己的决定上抛出错误的情况之一。 – Echizzle
您的类是否声明了“@ objc”,还是它是“NSObject”的子类? – NRitH