我正在使用UITextView
,并且尝试使用attributedText
属性作为用户类型来显示文本。
这是我当前的代码:
textView.attributedText = NSMutableAttributedString(
string: "",
attributes: [
NSFontAttributeName: UIFont(name: "AvenirNextLTPro-Regular", size: 12.5)!,
NSForegroundColorAttributeName: UIColor.colorFromCode(0x262626),
NSKernAttributeName: 0.5,
NSParagraphStyleAttributeName: paragraphStyle
]
)
问题在于,如果您提供一个空字符串,则当用户开始输入时,文本不会使用
attributedText
属性进行格式化。但是,我注意到是否提供了字符串,因为用户开始附加该字符串时,文本已使用
attributedText
属性进行了格式化。我认为可以完成我所需要的唯一方法是重写此函数,并在每次用户输入键时将文本设置为attributedText:
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool
还有其他更好的方法吗?
最佳答案
无需设置空的属性字符串,您需要使用typingAttributes
属性。
textView.typingAttributes = [
NSFontAttributeName: UIFont(name: "AvenirNextLTPro-Regular", size: 12.5)!,
NSForegroundColorAttributeName: UIColor.colorFromCode(0x262626),
NSKernAttributeName: 0.5,
NSParagraphStyleAttributeName: paragraphStyle
]
另请参见official documentation。
应用于用户输入的新文本的属性。