iOS - How to predefine TextView line height

南楼画角 提交于 2021-02-18 19:40:39

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!