簡體   English   中英

在#selector Swift 2.2中傳遞參數

[英]Pass on Argument in #selector Swift 2.2

我有一個方法:

func followUnfollow(followIcon: UIImageView, channelId: String) {
    let followUnfollow = followIcon
    let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.followIconTapped(_:)))
    followUnfollow.userInteractionEnabled = true
    followUnfollow.addGestureRecognizer(tapGestureRecognizer)
}

而且我有一種方法:

func followIconTapped(sender: UITapGestureRecognizer) {
    ...
}

一切正常。 但是我需要將channelId傳遞給followIconTapped()方法。

我嘗試這樣:

func followUnfollow(followIcon: UIImageView, channelId: String) {
    ...
    let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.followIconTapped(_:channelId)))
    ...
}

然后我嘗試抓住它:

func followIconTapped(sender: UITapGestureRecognizer, channelId: String) {
    ...
}

xCode表示channelId永遠不會使用。 為什么? 當我構建項目時,我沒有任何問題。 但是,如果我點擊followIcon,應用程序將崩潰。

請給我建議如何將channelId傳遞給followIconTapped()

創建通用的UITapGestureRecognizer而不是使用以下命令:

class CustomTapGestureRecognizer: UITapGestureRecognizer {
    var channelId: String?
}

也使用這個:

override func viewDidLoad() {
    super.viewDidLoad()

    let gestureRecognizer = CustomTapGestureRecognizer(target: self, action: #selector(tapped(_:))
    gestureRecognizer.channelId = "Your string"
    view1.addGestureRecognizer(gestureRecognizer)
}

func tapped(gestureRecognizer: CustomTapGestureRecognizer) {
    if let channelId = gestureRecognizer.channelId {
        //print
    }
}

嘗試為tapGestureRecognizer設置標簽,並根據標簽定義channelId

使用Selector時,不能將額外的參數傳遞給方法。 UITapGestureRecognizer可以處理帶有簽名的方法:

  • private dynamic func handleTap() { ... }
  • private dynamic func handleTapOn(gestureRecognizer: UIGestureRecognizer) { ... }

快速選擇器不會以其他方式進行驗證,然后檢查語法。 這就是為什么傳遞給操作方法的方法簽名沒有錯誤的原因。

如果您喜歡在handleTap方法中使用channelId ,則必須將變量保留在某個位置。 您可以在類中創建屬性,然后在其中存儲要在handleTap方法中使用的變量。

class YourClass: BaseClass {

    // MARK: - Properties

    private var channellId: String? = nil 

    // MARK: - API

    func followUnfollow(followIcon: UIImageView, channelId: String) {
        self.channelId = channelId
        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTapOn(_:)))
    }

    // MARK: - Callbacks

    private dynamic func handleTapOn(recognizer: UIGestureRecognizer) {
        if let channelId = self.channelId {
            // Do sth
        }
    }

}

暫無
暫無

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

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