我需要找出文本字段何时成为第一个通知我将要显示的键盘是否会阻碍UITextField的响应者。如果是这样,我想调整scrollview属性。
到目前为止,我有这个设置。我正在侦听调用以下选择器的UIKeyboardWillShow通知:
func keyboardWillAppear(notification:NSNotification)
{
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
{
if keyboardSize.intersects(textField.frame)
{
print("It intersects")
}
else
{
print("Houston, we have a problem")
}
}
注意:我尝试过UIKeyboardDidShow,但仍然没有成功。 UITextField是scrollView的子视图。
答案 0 :(得分:0)
工作样本:
@IBOutlet weak var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
//keyboard observers
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
}
func keyboardWillChange(notification:NSNotification)
{
print("Keyboard size changed")
if let keyboardSize = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? CGRect {
//convert gotten rect
let r = self.view.convert(keyboardSize, from: nil)
//test it
if r.intersects(textView.frame) {
print("intersects!!!")
}
}
}
答案 1 :(得分:0)
如何比较键盘的开始位置和文本的结束位置?
工作样本:
func keyboardWillAppear(notification:NSNotification)
{
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
{
if keyboardSize.origin.y < textField.frame.origin.y + textField.frame.size.height {
print("It intersects")
} else {
print("Houston, we have a problem")
}
}
}