找出UIKeyboard.frame与其他框架相交的时间?

时间:2017-02-14 16:27:35

标签: swift swift3 uitextfield uikit

我需要找出文本字段何时成为第一个通知我将要显示的键盘是否会阻碍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的子视图。

2 个答案:

答案 0 :(得分:0)

  1. 聆听键盘的尺寸变化
  2. 转换坐标
  3. 工作样本:

     @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")
        }
    }
}