在更改UITextView的边界时,TextContainer没有调整大小

时间:2015-10-02 17:59:19

标签: ios swift uitextview nstextcontainer

调整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)

目前,我不知道为什么它无法正常工作,无法找到解决方案。

1 个答案:

答案 0 :(得分:4)

把它扔在操场上。注释/以不同的方式设置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