2016-04-24 107 views
71

通过addTarget传递参数的新Xcode 7.3通常适用于我,但在这种情况下,它会将错误引发到标题中。有任何想法吗?当我尝试将其更改为@objc时,它会抛出另一个。谢谢!“#选择器”是指一种方法,不暴露于Objective-C

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

它调用

func didTapCommentButton(post: Post) { 
} 
+3

FeedViewController的类声明行是什么样的? didTapCommentButton是如何声明的?当您添加@objc时会得到什么错误? – vacawama

+1

更新,我编辑了我的帖子。我远离现在的电脑,所以我忘记了确切的错误信息,但它是XCode告诉我添加它然后在其自己的决定上抛出错误的情况之一。 – Echizzle

+2

您的类是否声明了“@ objc”,还是它是“NSObject”的子类? – NRitH

回答

45

的选择您需要使用@objc属性上didTapCommentButton(_:)#selector使用它。

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

你可以修复,通过使PostNSObject一个子类,但是这不会啦,因为参数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 
} 
+11

或者您可以标记方法'动态'。 –

+0

如果我想用它与全局函数? '@objc只能用于类的成员,@objc协议和类的具体扩展' – TomSawyer

+0

您不能将它用于全局函数。 –

8

尝试将选择器指向一个包装函数,该函数又调用您的委托函数。这对我有效。

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

-

func wrapperForDidTapCommentButton(post: Post) { 
    FeedViewController.didTapCommentButton(post) 
} 
+1

为我工作!仍然不知道为什么这是必要的,但我会接受! –

104

在我的情况下选择的功能是private。一旦我删除了private,错误消失了。 fileprivate也一样。

在斯威夫特4
您将需要添加@objc到函数声明。直到迅速4这是暗示推断。

+2

除'fileprivate'外。 – hstdt

+0

很棒的@shaked – jbouaziz

+0

@hstdt,所以如果你设置,'fileprivate'会解决吗? – Hemang

相关问题