簡體   English   中英

您如何知道要提供哪個字符串作為Swift函數的選擇器?

[英]How do you know which string to provide as a selector for Swift functions?

有時,當我在斯威夫特選擇工作(即Selector型),字符串文字,我提供了action ,以類似的方法參數targetForAction(_:withSender:)addTarget(_:action:)不會調用或地圖到我期望的實際Swift功能。

例如,當如下所示的MyResponder實例位於響應者鏈中時,使用字符串showImage:調用targetForAction(_:withSender)targetForAction(_:withSender)showImage: 怎樣才能知道為不同類型的Swift函數簽名提供正確的字符串文字以及所需和/或省略的參數標簽的選項?

import UIKit

class MyResponder: UIResponder {

    func showImage( named filename: String ) {
        print( "Loading image..." )
    }
}

class MyViewController: UIViewController {

    @IBAction func buttonTapped( sender: AnyObject? ) {
        if let responder = self.targetForAction( "showImage:", withSender: self ) as? MyResponder {
            responder.showImage(named: "my_image" )
        }
    }
}

經過評論者的反復試驗,錯誤和鼓勵,我設法弄清楚了這種模式!

字符串文字必須遵循從您的Swift函數的簽名轉換而來的Objective-C語法,這是一個有趣的@objc並不明顯,但在考慮諸如@objc屬性之類的有目的的東西時,這是@objc 在編寫更好的代碼示例時,我似乎已經弄清楚了映射的模式。

functionName +( With + First )+ : +( second )+ :

僅當需要參數標簽時(即不省略),才需要括號中的內容。 並記住要WithFirst

在下面的每個示例中, myObject將自身返回為提供的選擇器的目標,指示作為Selector提供的字符串文字實際上映射了它打算使用的Swift函數。

import UIKit

class MyObject : UIResponder {
    func someFunction() {}
    func someFunction(param:String) {}
    func someLabeledFunction(param param:String) {}
    func someTwoArgumentFunction(param1:String, param2:String) {}
    func someTwoArgumentNoLabelFunction(param1:String, _ param2:String) {}
    func someHalfLabeledTwoArgumentFunction(param1 param1:String, _ param2:String) {}
    func someCompletelyLabeledTwoArgumentFunction(param1 param1:String, param2:String) {}
}

let myObject = MyObject()
myObject.targetForAction("someFunction", withSender: nil)
myObject.targetForAction("someFunction:", withSender: nil)
myObject.targetForAction("someLabeledFunctionWithParam:", withSender: nil)
myObject.targetForAction("someTwoArgumentFunction:param2:", withSender: nil)
myObject.targetForAction("someTwoArgumentNoLabelFunction::", withSender: nil)
myObject.targetForAction("someHalfLabeledTwoArgumentFunctionWithParam1::", withSender: nil)
myObject.targetForAction("someCompletelyLabeledTwoArgumentFunctionWithParam1:param2:", withSender: nil)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM