TextContainer 在更改 UITextView 的边界时不调整大小

TextContainer isn't resizing while changing bounds of UITextView

调整 textView 大小后,我希望 textContainer 与 textView 大小相同(我希望文本与调整后的 textView 宽度相同)。所以我现在正在做的是我以编程方式创建一个 UITextView,然后(在 textView 中有或没有文本)我通过更改它的边界来调整 textView 的大小,但 textContainer 保持相同的大小(文本在比 textView 更小的矩形中看起来很糟糕)。

这是一些代码:

let textStorage = NSTextStorage()

let layoutManager = NSLayoutManager()
textStorage.addLayoutManager(layoutManager)

let textContainer = NSTextContainer()
layoutManager.addTextContainer(textContainer)

textContainer.widthTracksTextView = true
textContainer.heightTracksTextView = true

self.textView = UITextView(frame: textViewFrame, textContainer: textContainer)

之后:

self.textView.bounds = CGRect(x, y, newWidth, newHeight)

目前我不知道为什么它不起作用并且找不到解决方案。

把这个扔到操场上。评论out/in设置textView大小的不同方式。设置 bounds 确实不会更新容器。设置 framesize 可以。

import Foundation
import UIKit
import XCPlayground

var str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean feugiat purus a pharetra rhoncus. Phasellus eget velit risus. Duis varius et massa non pretium. Praesent sollicitudin egestas mi, non cursus eros ornare congue. Pellentesque ex leo, hendrerit posuere euismod ut, ultricies eleifend lectus. Phasellus eu interdum sem. Quisque ut condimentum justo. Integer non neque mauris. Vestibulum eu tellus ac nunc mollis maximus a vitae lectus. In hac habitasse platea dictumst. Sed neque sapien, elementum quis volutpat quis, dictum id ligula. Cras egestas finibus fermentum."

let textViewFrame = CGRectZero

let textStorage = NSTextStorage()

let layoutManager = NSLayoutManager()
textStorage.addLayoutManager(layoutManager)

let textContainer = NSTextContainer(size: textViewFrame.size)
layoutManager.addTextContainer(textContainer)

textContainer.widthTracksTextView = true
textContainer.heightTracksTextView = true

var textView = UITextView(frame: textViewFrame, textContainer: textContainer)
XCPShowView("MyView", view: textView)

textView.text = str

//textView.bounds = CGRect(x: 0, y: 0, width: 200, height: 200)
//textView.frame = CGRect(x: 0, y: 0, width: 200, height: 200)
textView.frame.size = CGSize(width: 200, height: 200)

//textView.bounds = CGRect(x: 0, y: 0, width: 400, height: 200)
//textView.frame = CGRect(x: 0, y: 0, width: 400, height: 200)
textView.frame.size = CGSize(width: 400, height: 200)

未来的读者,如果您是因为旋转 UITextView 而来到这里:Transform UITextView