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

旋转UITextView后文本提前换行的原因分析与解决方案

问题原因分析

当你通过CGAffineTransform旋转UITextView时,只是改变了它在屏幕上的视觉渲染角度,但UITextView内部的文本排版逻辑依然基于它原始的frame尺寸(宽300,高200)来计算换行位置。

旋转90度后,UITextView在视觉上的水平可用宽度变成了原来的高度(200),但文本排版系统仍在使用原始的宽度(300)来计算每行能容纳的字符数。这就导致文本在视觉上还没到“行尾”,就已经按照300的宽度排满换行,看起来像是提前换行了。

解决办法

有两种简单有效的方案可以解决这个问题:

方案1:交换frame的宽高后再旋转

既然旋转会交换视觉上的宽高,我们可以先调整UITextView的原始frame,把宽和高互换,再执行旋转操作。这样文本排版的尺寸就会和旋转后的视觉尺寸匹配:

// 交换原始宽高:原本是width 300, height 200,现在改成width 200, height 300
let textView = UITextView(frame: CGRect(x: 0, y: 0, width: 200, height: 300))
textView.transform = CGAffineTransform(rotationAngle: .pi / 2)
textView.text = "This is some long sample text to show the issue I am facing. Notice that the text is broken onto the next line well before the end of the UITextView."
textView.backgroundColor = .red
textView.center = view.center
view.addSubview(textView)

方案2:直接修改textContainer的尺寸

UITextView的文本排版由textContainer控制,我们可以直接修改它的尺寸,让排版逻辑使用旋转后的实际可用空间:

let textView = UITextView(frame: CGRect(x: 0, y: 0, width: 300, height: 200))
textView.transform = CGAffineTransform(rotationAngle: .pi / 2)
// 设置textContainer的尺寸为旋转后的可用宽高(即原frame的高和宽)
textView.textContainer.size = CGSize(width: textView.frame.height, height: textView.frame.width)
textView.text = "This is some long sample text to show the issue I am facing. Notice that the text is broken onto the next line well before the end of the UITextView."
textView.backgroundColor = .red
textView.center = view.center
view.addSubview(textView)

这两种方案都能让文本的换行逻辑匹配旋转后的视觉边界,解决提前换行的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:25:08