UITextView不显示文本咨询:自定义NSTextContainer后仅显空白方块
问题
我了解到UITextView由三大组件构成:Layout Manager、TextView和Text Storage。我的使用场景非常简单,无需自定义Text Storage和Layout Manager,但以下代码运行后仅显示一个空白方块,请问原因是什么?
代码:
let legendContainer = NSTextContainer(size: CGSize(width: 100, height: 100)) let legend = UITextView(frame: CGRect(x: 20, y: 150, width: 200, height: 200), textContainer: legendContainer) legend.textColor = UIColor.lightGray legend.backgroundColor = UIColor.darkGray legend.font = UIFont.boldSystemFont(ofSize: 14.0) legend.text = "My text" addSubview(legend)
原因分析与解决办法
嘿,我来帮你搞定这个问题~ 你现在的代码里,手动创建了NSTextContainer,但没有给它关联对应的NSLayoutManager和NSTextStorage,这就是文本显示不出来的核心原因。
UITextView的三大组件是互相依赖的:
NSTextStorage负责存储文本内容NSLayoutManager负责把文本内容布局到NSTextContainer里NSTextContainer定义了文本显示的区域范围
当你手动传入自定义的NSTextContainer给UITextView时,系统不会自动帮你关联另外两个组件,所以哪怕你设置了legend.text,也没有对应的布局管理器来处理文本渲染,自然就只显示你设置的深色背景方块了。
解决办法很简单,有两种方式:
- 不手动创建NSTextContainer:如果你不需要自定义文本容器,直接用UITextView的默认初始化方法就行,系统会自动帮你完成三大组件的关联:
let legend = UITextView(frame: CGRect(x: 20, y: 150, width: 200, height: 200)) // 后续设置属性和之前一样 legend.textColor = UIColor.lightGray legend.backgroundColor = UIColor.darkGray legend.font = UIFont.boldSystemFont(ofSize: 14.0) legend.text = "My text" addSubview(legend)
- 手动关联三大组件:如果你确实需要自定义
NSTextContainer,那得把三个组件手动绑定起来:
// 1. 创建文本存储 let textStorage = NSTextStorage(string: "My text") // 2. 创建布局管理器 let layoutManager = NSLayoutManager() // 3. 创建文本容器 let legendContainer = NSTextContainer(size: CGSize(width: 100, height: 100)) // 关联组件 textStorage.addLayoutManager(layoutManager) layoutManager.addTextContainer(legendContainer) // 初始化UITextView let legend = UITextView(frame: CGRect(x: 20, y: 150, width: 200, height: 200), textContainer: legendContainer) legend.textColor = UIColor.lightGray legend.backgroundColor = UIColor.darkGray legend.font = UIFont.boldSystemFont(ofSize: 14.0) // 注意:这里不需要再设置legend.text了,内容已经在textStorage里 addSubview(legend)
这样修改后,文本就能正常显示啦~
内容的提问来源于stack exchange,提问作者Ddefin Orsstt
相关产品推荐
相关产品推荐

