2016-04-24 102 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

相關問題