Ddefin Orsstt
Ddefin Orsstt

Reputation: 198

Why is UITextView not showing text?

I have read that three components go into TextView - layout manager, TextView and Text Storage. I have a very simple use case and can get by without storage and custom layout manager.

Why does the following show only a blank square as described by the legend frame?

 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)

enter image description here

Upvotes: 0

Views: 285

Answers (1)

matt
matt

Reputation: 534966

It's because your text container lacks the rest of the text kit stack. You may only need the text container, but the text container still needs a layout manager and a text storage.

let lm = NSLayoutManager()
let ts = NSTextStorage()
ts.addLayoutManager(lm)
let tc = NSTextContainer(size: someSize)
lm.addTextContainer(tc)
let tv = UITextView(frame:someFrame, textContainer:tc)

Upvotes: 1

Related Questions