I found this which works perfectly on UITextViews linked to the viewController, but I can not figure out how to get it to work correctly for a UITextView created within a separate class.
https://stackoverflow.com/a/41387780/8635708
I want the view to be three units (character height) tall and the contents to be centered vertically.
On the other hand, if I make the view 4 units tall, it looks good - but I don't have the space for that.
Here is what I did (which seems to work for the single line).
class TestClass: UIView {
var titleView1 = UITextView()
var titleView2 = UITextView()
override func layoutSubviews() {
titleView1.centerVertically()
titleView2.centerVertically()
}
override func draw(_ rect: CGRect) {
super.draw(rect)
let h = 3 * GlobalConstants.fontSize // 3 * 14 = 42
var title = "Single Line"
var bounds = CGRect(x: 10, y: 10, width: 100, height: h)
displayTitle(str: title, column: &titleView1, bounds: bounds)
title = "First Line\nSecondLine"
bounds = CGRect(x: 120, y: 10, width: 100, height: h)
displayTitle(str: title, column: &titleView2, bounds: bounds)
}
func displayTitle(str: String, column: inout UITextView, bounds: CGRect) {
let view = UITextView(frame: bounds)
let attributes: [NSAttributedString.Key: Any] = [
.foregroundColor: UIColor.blue,
.font: UIFont.italicSystemFont(ofSize: 16)
]
let attributedText = NSMutableAttributedString(string: str, attributes: attributes)
view.attributedText = attributedText
view.textAlignment = .center
view.centerVertically()
self.autoresizesSubviews = true
self.addSubview(view)
}
}
I don't believe vertical alignment can be done simply with an NSAttributedString
but if possible, please let me know how!
Thanks!