传递#selector Swift 2.2中的Argument

时间:2016-08-12 13:26:33

标签: ios swift2

我有一个方法:

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

3 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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

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

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

如果您希望在channelId方法中使用handleTap,则必须将变量保留在某个位置。您可以在类中创建属性并将变量存储在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
        }
    }

}