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

K.K*_*K.K 2 uitextview ios nstextcontainer swift

调整 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)
Run Code Online (Sandbox Code Playgroud)

然后:

self.textView.bounds = CGRect(x, y, newWidth, newHeight)
Run Code Online (Sandbox Code Playgroud)

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

R M*_*nke 6

把这个扔到操场上。注释掉/以不同的方式设置 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)
Run Code Online (Sandbox Code Playgroud)

未来的读者,如果你在这里是因为你正在旋转 UITextView :转换 UITextView