TextContainer не изменяет размер при изменении границ 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)
В настоящее время у меня нет идей, почему это не работает и не могу найти решение.
1 ответ
Брось это на игровую площадку. Закомментируйте / разными способами, чтобы установить размер textView. Настройка bounds
действительно не обновляет контейнер. установка frame
или же size
делает.
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