问题
I've some UITextView
declared as the following
lazy var inputTextView: UITextView = {
let tv = UITextView()
tv.tintColor = UIColor.darkGray
tv.font = UIFont.systemFont(ofSize: 17)
tv.backgroundColor = UIColor.white
return tv
}()
I've been searching how can I predefine the line height for this UITextView
so whenever I write a long text, when it reaches the end of the line and goes to the following line, the spacing would be bigger than the default.
I've tried using the following inside the UITextView
declaration:
let style = NSMutableParagraphStyle()
style.lineSpacing = 40
let attributes = [NSParagraphStyleAttributeName : style]
tv.attributedText = NSAttributedString(string: "", attributes:attributes)
Which would become:
lazy var inputTextView: UITextView = {
let tv = UITextView()
tv.tintColor = UIColor.darkGray
tv.font = UIFont.systemFont(ofSize: 17)
tv.backgroundColor = UIColor.white
let style = NSMutableParagraphStyle()
style.lineSpacing = 40
let attributes = [NSParagraphStyleAttributeName : style]
tv.attributedText = NSAttributedString(string: "", attributes:attributes)
return tv
}()
It only works if I pre-insert some text in the attributedText
property but since the text is empty in the beginning it will not use those properties and it will be set as default.
How can I increase the default line height and keep it whenever I'm writing in the UITextView
?
Thanks ;)
回答1:
I solved the issue. The problem was that I shouldn't set the attributedText
to be set according to the attributes because when we start typing the attributes are gone.
Instead I set the typingAttributes
to be equal to what I desire so whenever I type in the attributes don't get lost.
Final version:
lazy var inputTextView: UITextView = {
let tv = UITextView()
tv.tintColor = UIColor.darkGray
tv.font = UIFont.systemFont(ofSize: 17)
tv.backgroundColor = UIColor.white
let spacing = NSMutableParagraphStyle()
spacing.lineSpacing = 4
let attr = [NSParagraphStyleAttributeName : spacing]
tv.typingAttributes = attr
return tv
}()
回答2:
Those who are looking for Swift 4 version
let spacing = NSMutableParagraphStyle()
spacing.lineSpacing = 7
spacing.alignment = .center
textView.typingAttributes = [NSAttributedStringKey.paragraphStyle.rawValue: spacing,
NSAttributedStringKey.font.rawValue: UIFont.systemFont(ofSize: 14)]
From iOS 11, Apple clears the text attributes after every character. So you have to set the typing attributes in,
func textViewShouldBeginEditing(_ textView: UITextView) -> Bool
来源:https://stackoverflow.com/questions/44400260/ios-how-to-predefine-textview-line-height