You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

iOS(iPhone X)如何使UITextView自定义inputView高度与默认键盘一致?

解决iPhone X上UITextView自定义inputView高度与默认键盘不一致的问题

兄弟,我太懂你这个iPhone X上的坑了!之前我也踩过一模一样的——自定义inputView总是比默认键盘矮一截,其实根源就是**底部安全区(Safe Area)**的问题。iPhone X及以后的机型底部有34pt的安全区,系统默认键盘会自动延伸覆盖这个区域,但自定义inputView默认是停在安全区上方的,所以高度就差了这34pt。

下面给你一套靠谱的解决方案,亲测有效:

核心思路

通过监听系统键盘的弹出通知,获取键盘的真实高度(包含安全区),然后直接把自定义inputView的高度设置成这个值,完美对齐默认键盘。

完整代码示例

class ViewController: UIViewController {
    let textView = UITextView()
    let button = UIButton()
    var keyboardView = UIView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 先配置textView的基础布局
        textView.frame = CGRect(x: 20, y: 100, width: view.bounds.width - 40, height: 200)
        textView.borderStyle = .roundedRect
        view.addSubview(textView)
        
        // 初始化自定义inputView
        keyboardView.backgroundColor = .lightGray
        keyboardView.translatesAutoresizingMaskIntoConstraints = false
        textView.inputView = keyboardView
        
        // 给inputView设置宽度约束(和屏幕同宽)
        keyboardView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
        
        // 注册键盘弹出通知,获取真实高度
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(keyboardWillShow(_:)),
            name: UIResponder.keyboardWillShowNotification,
            object: nil
        )
    }
    
    @objc private func keyboardWillShow(_ notification: Notification) {
        // 从通知里取出键盘最终的frame
        guard let keyboardFrame = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else {
            return
        }
        // 拿到包含安全区的键盘真实高度
        let keyboardRealHeight = keyboardFrame.height
        
        // 给自定义inputView设置高度约束
        keyboardView.heightAnchor.constraint(equalToConstant: keyboardRealHeight).isActive = true
    }
    
    // 记得在销毁时移除通知监听,避免内存泄漏
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

关键注意点

  1. 别混用Auto Layout和AutoresizingMask:你之前用的autoresizingMask = .flexibleHeight容易和Auto Layout冲突,纯用约束更可靠。
  2. 监听正确的通知:用UIKeyboardWillShowNotification而不是DidShow,这样能在键盘弹出前就调整好inputView高度,避免视觉跳动。
  3. 适配所有机型:这个方法不只是针对iPhone X,其他机型的键盘高度也能准确获取,完美适配。

内容的提问来源于stack exchange,提问作者Daniel James

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:13:33