我的第一个问题是如何在textView中更改单词示例“test”的字体,并且@bkrl和@Torongo正确回答了它。
func changeAllOccurence(of string: String, font: UIFont) -> NSAttributedString {
let attributedString = NSMutableAttributedString(string: self)
var range = NSMakeRange(0, attributedString.mutableString.length)
while(range.location != NSNotFound)
{
range = attributedString.mutableString.range(of: string, options: .caseInsensitive, range: range)
if(range.location != NSNotFound)
{
attributedString.addAttribute(NSFontAttributeName,
value: font,
range: range)
range = NSMakeRange(range.location + range.length, self.characters.count - (range.location + range.length));
}
}
return attributedString
}
由于我还不熟悉上面的代码,我尝试添加几行以便对代码进行概括,以便它可以用于字符串数组而不仅仅是一个字符串。 但是肯定它没有用,因为它改变了最后一个单词的字体,这是合理的,因为最后的改变将是最后一个单词,即“用法”:
let words = ["example", "usage"]
for word in words {
let attributedText = text.changeAllOccurence(of: word, font: UIFont.boldSystemFont(ofSize: 17))
textview.attributedText = attributedText
}
有人可以建议如何改进@Toromgo提供的代码,以便处理任何字符串数组而不仅仅是一个字符串吗?
答案 0 :(得分:3)
您可以创建扩展程序,如:
extension String {
func change(font: UIFont, of string: String) -> NSAttributedString {
let attributedString = NSMutableAttributedString(string: self)
let subStringRange = attributedString.mutableString.range(of: string,
options: .caseInsensitive)
if subStringRange.location != NSNotFound {
attributedString.addAttribute(NSFontAttributeName,
value: font,
range: subStringRange)
}
return attributedString
}
}
用法:
let text = "This is example of usage extension"
let attributedText = text.change(font: UIFont.boldSystemFont(ofSize: 17), of: "example")
textView.attributedText = attributedText
希望有所帮助!
答案 1 :(得分:2)
由于您已更改了问题,我已相应更新了我的答案。请试试这个:
extension String {
func changeAllOccurence(of strings: [String], font: UIFont) -> NSAttributedString {
let attributedString = NSMutableAttributedString(string: self)
for eachString in strings {
var range = NSMakeRange(0, attributedString.mutableString.length)
while(range.location != NSNotFound)
{
range = attributedString.mutableString.range(of: eachString, options: .caseInsensitive, range: range)
if(range.location != NSNotFound)
{
attributedString.addAttribute(NSFontAttributeName,
value: font,
range: range)
range = NSMakeRange(range.location + range.length, self.characters.count - (range.location + range.length));
}
}
}
return attributedString
}
}
我已经运行了代码并且它正在运行。