【问题标题】:Find out when UIKeyboard.frame intersects with other frame?找出 UIKeyboard.frame 何时与其他框架相交?
【发布时间】:2017-02-14 16:27:35
【问题描述】:

我需要找出文本字段何时成为第一响应者,以通知我将要显示的键盘是否会阻碍 UITextField。如果是这样,我想调整滚动视图属性。

到目前为止,我已经完成了这个设置。我正在监听调用以下选择器的 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 的子视图。

【问题讨论】:

    标签: swift swift3 uitextfield uikit


    【解决方案1】:
    1. 听键盘大小变化
    2. 转换坐标

    工作样本:

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

    【讨论】:

    • @Dalj-Djan 这有帮助。但是我只需要在转换函数中做一个小的调整,所以,而不是从 nil 到我的 scrollView,因为我的文本字段是来自 scrollView 的子视图。谢谢兄弟。
    【解决方案2】:

    如何比较键盘的起始位置和文本的结束位置?

    工作样本:

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

    【讨论】:

      猜你喜欢
      • 2011-06-08
      • 1970-01-01
      • 2016-12-12
      • 1970-01-01
      • 2013-03-10
      • 1970-01-01
      • 2010-10-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多