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

iOS TextView无法自动换行及自适应高度问题排查求助

解决TextView自动换行与自适应高度失效问题

我帮你排查了代码里的问题,确实是AutoLayout约束和TextView的布局更新逻辑出了问题,咱们一步步来修复:

问题1:TextView底部约束绑定错误

你在iOS11+的代码里把commentTextView的bottom约束绑到了safeAreaLayoutGuide.bottomAnchor,但作为inputAccessoryView,这个自定义View的底部已经自动适配了安全区域,绑定到safeArea会让TextView的底部被截断,导致长文本无法显示,也没法自适应高度。

修复方法:把TextView的bottom约束改为绑定到自身的bottomAnchor:

if #available(iOS 11.0, *){
    commentTextView.anchor(top: topAnchor, left: leftAnchor, bottom: bottomAnchor, right: submitButton.leftAnchor, paddingTop: 0, paddingLeft: 12, paddingBottom: 0, paddingRight: 0, width: 0, height: 0)
}else{
    commentTextView.anchor(top: topAnchor, left: leftAnchor, bottom: bottomAnchor, right: submitButton.leftAnchor, paddingTop: 0, paddingLeft: 12, paddingBottom: 0, paddingRight: 0, width: 0, height: 0)
}

问题2:文本变化时未触发布局更新

你写了textFieldDidChange方法,但这个方法并没有被正确调用(它不是UITextViewDelegate的标准方法),导致文本变化时,父视图不知道需要重新计算高度,TextView的自适应高度也就失效了。

修复方法:实现UITextViewDelegate的textViewDidChange方法,并在其中触发父视图重新计算内在尺寸:

func textViewDidChange(_ textView: UITextView) {
    let isCommentValid = textView.text?.count ?? 0 > 0
    submitButton.isEnabled = isCommentValid
    // 通知inputAccessoryView重新计算高度
    self.invalidateIntrinsicContentSize()
}

可选优化:调整文本内边距

默认的TextView文本边距可能有点紧凑,你可以添加内边距让显示更美观:

lazy var commentTextView: UITextView = {
    let textView = UITextView()
    textView.delegate = self
    textView.isScrollEnabled = false
    textView.backgroundColor = .red
    textView.font = UIFont.boldSystemFont(ofSize: 12)
    textView.textContainer.lineBreakMode = .byWordWrapping
    // 添加内边距
    textView.textContainerInset = UIEdgeInsets(top: 8, left: 0, bottom: 8, right: 0)
    textView.textContainer.lineFragmentPadding = 0
    return textView
}()

验证修改后的效果

做完这些修改后:

  • 长文本会自动按单词换行,不会被截断
  • 输入文本时,TextView的高度会自动扩展,整个inputAccessoryView也会跟着自适应高度
  • 删除文本时,高度会自动收缩回合适的尺寸

内容的提问来源于stack exchange,提问作者Ron Baker

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:30:18