如何将多个参数传递给Swift #selector?

时间:2019-03-28 02:42:59

标签: ios swift

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

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 {

}

2 个答案:

答案 0 :(得分:2)

传递数据的更简单方法是创建自定义类。 示例我需要通过 let attributedString = NSMutableAttributedString(string: textView.text) let range = (textView.text as NSString).range(of: "\(url)") attributedString.addAttribute(.link, value: 1, range: range) attributedString.addAttribute(.underlineStyle, value: 1, range: range) attributedString.addAttribute(.underlineColor, value: UIColor.blue, range: range) textView.attributedText = attributedString 传递数据。

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

UITapGestureRecognizer
class CustomTapGesture: UITapGestureRecognizer {
    var data: YourData
}

#selector 功能

let tapGesture = CustomTapGesture(target: self, action: #selector(tapGesture(_:)))
tapGesture.data = yourData
yourView.addGestureRecognizer(tapGesture)

答案 1 :(得分: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也许可以为您提供即需即用的需求。查看答案here

相关问题