我的UITextView
应用中有一个swift
,我在viewDidLoad
设置了字体:
let font = UIFont(name: "AppleSDGothicNeo-Light", size: 16.0)
myTextView.font = font
它运行正常,当我运行应用程序并在文本视图中写入内容时,我看到:
现在,我有一个检查给定文本的方法,并在其中查找并突出显示hashtags
。方法如下:
func formatTextInTextView(textView: UITextView) {
textView.scrollEnabled = false
let selectedRange = textView.selectedRange
let text = textView.text
// This will give me an attributedString with the base text-style
let attributedString = NSMutableAttributedString(string: text)
let regex = try? NSRegularExpression(pattern: "#(\\w+)", options: [])
let matches = regex!.matchesInString(text, options: [], range: NSMakeRange(0, text.characters.count))
for match in matches {
let matchRange = match.rangeAtIndex(0)
let titleDict: NSDictionary = [NSForegroundColorAttributeName: UIColor(red: 244/255, green: 137/255, blue: 0/255, alpha: 1.0), NSFontAttributeName: font!]
attributedString.addAttributes(titleDict as! [String : AnyObject], range: matchRange)
}
textView.attributedText = attributedString
textView.selectedRange = selectedRange
textView.scrollEnabled = true
}
我将此方法添加到:
func textViewDidChange(textView: UITextView) {
formatTextInTextView(textView)
}
现在,对于每个用户的输入,我都会动态检查它是否是一个#标签,如果是,则将文本突出显示为橙色。至少它应该是理论上的。因此,当启用该方法时会发生这种情况:
一旦我开始写文字:
(这对我来说似乎是一个系统字体)
当我添加hashtag:
它适用于主题标签,但文本的其余部分 - 似乎 - 默认样式。这里的问题是什么? :|
答案 0 :(得分:1)
您需要在最初创建属性字符串时指定所需的字体,而不仅仅是具有不同颜色的部分。
func formatTextInTextView(textView: UITextView) {
textView.scrollEnabled = false
let selectedRange = textView.selectedRange
let text = textView.text
let titleDict: NSDictionary = [NSFontAttributeName: font!]
// This will give me an attributedString with the desired font
let attributedString = NSMutableAttributedString(string: text, attributes: titleDict)
let regex = try? NSRegularExpression(pattern: "#(\\w+)", options: [])
let matches = regex!.matchesInString(text, options: [], range: NSMakeRange(0, text.characters.count))
for match in matches {
let matchRange = match.rangeAtIndex(0)
let titleDict: NSDictionary = [NSForegroundColorAttributeName: UIColor(red: 244/255, green: 137/255, blue: 0/255, alpha: 1.0)]
attributedString.addAttributes(titleDict as! [String : AnyObject], range: matchRange)
}
textView.attributedText = attributedString
textView.selectedRange = selectedRange
textView.scrollEnabled = true
}