Extend iOS 11 Safe Area to include the keyboard

后端 未结 5 725
忘了有多久
忘了有多久 2020-12-25 14:53

The new Safe Area layout guide introduced in iOS 11 works great to prevent content from displaying below bars, but it excludes the keyboard. That means that when a keyboard

5条回答
  •  余生分开走
    2020-12-25 15:24

    bottom inset:

        var safeAreaBottomInset: CGFloat = 0
        if #available(iOS 11.0, *) {
            safeAreaBottomInset = UIApplication.shared.keyWindow?.safeAreaInsets.bottom ?? 0
        }
    

    whole keyboard function:

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    
        NotificationCenter.default.addObserver(self, selector: #selector(self.onKeyboardWillChangeFrame), name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
    }
    
    @objc private func onKeyboardWillChangeFrame(_ notification: NSNotification) {
            guard let window = self.view.window,
                let info = notification.userInfo,
                let keyboardFrame = info[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect,
                let duration = info[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval,
                let animationCurve = info[UIResponder.keyboardAnimationCurveUserInfoKey] as? NSNumber
            else {
                return
            }
    
            var safeAreaInset: CGFloat = 0
            if #available(iOS 11.0, *) {
                safeAreaInset = UIApplication.shared.keyWindow?.safeAreaInsets.bottom ?? 0
            }
            self.keyboardConstraint.constant = max(0, self.view.frame.height - window.convert(keyboardFrame, to: self.view).minY - safeAreaInset)
    
            UIView.animate(
                withDuration: duration,
                delay: 0,
                options: [UIView.AnimationOptions(rawValue: animationCurve.uintValue), .beginFromCurrentState],
                animations: { self.view.layoutIfNeeded() },
                completion: nil
            )
        }
    

提交回复
热议问题