2014-10-11 48 views
-1

我使用代碼將操作分配給我的按鈕時,他們創建。 下面的代碼不工作,沒有任何問題:NSSelector崩潰我的鍵盤應用程序沒有任何錯誤

button.addTarget(self, action: didTapDot, forControlEvents: .TouchUpInside) 

按鈕按鈕對象,didTapDot是在同一個類中的函數的名稱,當按鈕被觸摸時功能被激活,那麼點標誌可以寫在屏幕上。

現在我正在嘗試製作一個通用代碼,可以稍後在單行代碼中以非常相似的方式操作所有按鈕。我做了一個叫做didTap(content)的函數。現在和之前一樣,我想將特定的didTapDot替換爲didTap(內容)。

let tapAction = "didTap("+content+")" 
let tapActionSelector = NSSelectorFromString(tapAction) 
button.addTarget(self, action: tapActionSelector, forControlEvents: .TouchUpInside) 

我以最「安全」的方式避免了問題。 「action:」需要一個NSSelector,所以爲了讓它首先創建一個我想發送的函數的String,然後我將它轉換爲NSSelector。

現在,Xcode仍然顯示0錯誤和0警告。我運行模擬器。鍵盤成功顯示。我點擊一個創建的按鈕 - 崩潰。我不知道發生了什麼做錯了這裏:(

備案,這裏的控制檯給我的崩潰後的錯誤:

2014-10-11 14:42:43.315 AppName[7634:561153] plugin gilad.AppName.Extension interrupted 2014-10-11 14:42:44.414 AppName[7634:561075] viewServiceDidTerminateWithError:: Error Domain=_UIViewServiceInterfaceErrorDomain Code=3 "The operation couldn’t be completed. (_UIViewServiceInterfaceErrorDomain error 3.)" UserInfo=0x7f900ad206b0 {Message=Service Connection Interrupted}

因此,任何想法可能出了錯

+1

[將參數附加到Swift中的button.addTarget動作](http://stackoverflow.com/questions/24814646/attach-parameter-to-button-addtarget-action-in-swift) – 2014-10-11 12:10:39

+2

您可能不能*爲操作方法添加任意參數。 – 2014-10-11 12:11:27

+0

您的意思是_must_包含的功能無法接收任何關於是誰的信息? 那麼如何才能實現該代碼的方式,將解決每次不同的按鈕? – user2046387 2014-10-11 13:17:11

回答

1

? 。我認爲這可以幫助我找到了你的問題,因爲我得到當我的鍵盤終止了同樣的錯誤,但我認爲是不相關。在任何情況下,我有同樣的任務,這是我的解決方案:

//didTap function 
    func didTap(sender:UIButton){ 
     var proxy = textDocumentProxy as UITextDocumentProxy 
     proxy.insertText(sender.titleForState(.Normal)!) 
    } 

    //how to use when you set up your keyboard 
    button.setTitle(key.label,forState: .Normal) 
    button.addTarget(self, action: "didTap:", forControlEvents: .TouchUpInside) 

請注意addTarget中函數名稱末尾的「:」。它告訴底層框架有一個預期參數(發件人)。

希望它有幫助。

相關問題