在#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()

尝试为 tapGestureRecognizer 设置标签并根据标签定义 channelId

创建一个通用的 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
    }
}

当您使用 Selector 时,您不能将额外的参数传递给您的方法。 UITapGestureRecognizer 可以处理带有签名的方法:

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

swift 中的选择器不会以其他方式验证然后检查句法。这就是为什么没有与您传递给操作方法的方法签名相关的错误。

如果您喜欢在 handleTap 方法中使用 channelId,您必须将变量保存在某个地方。您可以在 class 中创建 属性 并将您的变量存储在 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
        }
    }

}