1

我想将第二个参数传递给来自另一个函数的选择器函数:

func bindToKeyboardNew(constraint: NSLayoutConstraint) { // <- this parameter 
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:constraint:)), name: UIResponder.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
}

@objc func keyboardWillShow(_ notification: NSNotification, constraint: NSLayoutConstraint) // <- To This selector {

}
4

2 回答 2

3

传递数据的更简单方法是创建自定义类。示例我需要通过UITapGestureRecognizer.

首先,创建一个自定义UITapGestureRecognizer并定义一个实例,它是您的数据

class CustomTapGesture: UITapGestureRecognizer {
    var data: YourData
}
let tapGesture = CustomTapGesture(target: self, action: #selector(tapGesture(_:)))
tapGesture.data = yourData
yourView.addGestureRecognizer(tapGesture)

#选择器函数

@objc func tap(_ sender: UITapGestureRecognizer) {
    if let sender = sender as? CustomTapGesture {
       yourData = sender.data
       // do something with your data
    }
}
于 2019-03-28T04:21:43.760 回答
0

正如@rmaddy 在评论中提到的那样,这不能按照您要求的方式完成。

在这部分

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:constraint:)), name: UIResponder.keyboardWillShowNotification, object: nil)

无法控制选择器的发送方式(以及使用什么参数)。

UIKit在它的私有实现内部做了这样的事情(让我们暂时忽略它的实现并不是真正的 Swift,这在这里并不重要):

NotificationCenter.default.post(name: NSNotification.Name(rawValue: UIResponder.keyboardWillShowNotification), object: uiwindow, userInfo: systemUserInfoForKeyboardShow)

这意味着选择器已经发送,并且无法向可选的 userInfo 添加额外的内容(如果.post(...)代码中确实发生了这种情况,您可以这样做,但这里不是这种情况)。

您需要另一种方法NSLayoutConstraint来访问键盘选择器显示/隐藏处理程序中的当前对象。也许它应该是你的一个属性ViewController,也许是你的某种状态,AppDelegate或者可能是完全不同的东西,不知道你的代码的其余部分是不可能的。

编辑:根据您添加的评论,我假设您有这样的事情:

class ViewController: UIViewController {
    @IBOutlet var constraint: NSLayoutConstraint?
}

如果是这样,您可以简单地访问 VC 中选择器处理程序中的约束:

class ViewController: UIViewController {
    @IBOutlet var constraint: NSLayoutConstraint?
    @objc func keyboardWillShow(_ notification: NSNotification) {
       //do something with the constraint 
       print(constraint)
    }
}

还有一个专用的UIKeyboardWillChangeFrameNotification,也许它可以为您提供开箱即用的东西。在这里查看答案

于 2019-03-29T15:32:29.653 回答