微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

xcode – ‘#selector’是指不暴露于Objective-C的方法

通过addTarget传递参数的新Xcode 7.3通常适用于我,但在这种情况下,它会在标题中抛出错误。有任何想法吗?当我尝试将其更改为@objc时,它会抛出另一个异常

谢谢!

cell.commentButton.addTarget(self,action: #selector(FeedViewController.didTapCommentButton(_:)),forControlEvents: UIControlEvents.TouchUpInside)

它被调用的选择器

func didTapCommentButton(post: Post) {
}

解决方法

您需要在didTapCommentButton(_ :)上使用@objc属性将其用于#selector。

你说你这样做,但你有另一个错误。我的猜测是,新的错误是Post不是与Objective-C兼容的类型。如果所有参数类型及其返回类型与Objective-C兼容,则只能向Objective-C公开一种方法。

你可以通过发布NSObject的子类来修复,但这并不重要,因为didTapCommentButton(_ :)的参数不会是Post。动作功能的参数是动作的发送者,该发送方将是commentButton,这可能是一个UIButton。你应该这样声明didTapCommentButton:

@objc func didTapCommentButton(sender: UIButton) {
    // ...
}

然后,您将面临获取与点击按钮相对应的帖子的问题。有多种方法可以得到它。这是一个。

我收集(因为你的代码是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
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐