iOS - 如何预定义 TextView 行高 [英] iOS - How to predefine TextView line height
问题描述
我有一些 UITextView
声明如下
lazy var inputTextView: UITextView = {
let tv = UITextView()
tv.tintColor = UIColor.darkGray
tv.font = UIFont.systemFont(ofSize: 17)
tv.backgroundColor = UIColor.white
return tv
}()
我一直在搜索如何为这个 UITextView
预定义行高,所以每当我写一个长文本时,当它到达行尾时到下一行,间距将大于默认值.
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.
我尝试在 UITextView
声明中使用以下内容:
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)
会变成:
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
}()
它仅在我在 attributedText
属性中预先插入一些文本时才有效,但由于文本一开始是空的,因此不会使用这些属性,而是将其设置为默认值.
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.
当我在 UITextView
中书写时,如何增加默认行高并保持它?
How can I increase the default line height and keep it whenever I'm writing in the UITextView
?
谢谢;)
推荐答案
那些正在寻找 Swift 4 版本的人
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)]
从 iOS 11 开始,Apple 会清除每个字符后的文本属性.所以你必须设置输入属性,
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
这篇关于iOS - 如何预定义 TextView 行高的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!