我正在尝试将UILabel中所有“(RUR'U')”实例的文本颜色更改为红色,并将其他(ALG_HERE)实例的文本颜色更改为不同的颜色,例如蓝色和橙色。
到目前为止,我有这个
@IBOutlet weak var algName: UILabel?
algToShow = UserDefaults.standard.string(forKey: "ollShowAlg\(OLLData.OLLCasesList[selectedCases[scrambleNumber]-1]._id)")!
//let text = "This is the text and i want to replace something"
let mutableAttributedString = NSMutableAttributedString(string: algToShow)
var searchRange = NSRange(location: 0, length: algToShow.count)
var foundRange1 = NSRange()
var foundRange2 = NSRange()
var foundRange3 = NSRange()
var foundRange4 = NSRange()
var foundRange5 = NSRange()
while searchRange.location < algToShow.count {
searchRange.length = algToShow.count - searchRange.location
foundRange1 = (algToShow as NSString).range(of: "(R U R' U')", options: NSString.CompareOptions.caseInsensitive, range: searchRange) //sexy
foundRange2 = (algToShow as NSString).range(of: "(R' F R F')", options: NSString.CompareOptions.caseInsensitive, range: searchRange) //sledge
foundRange3 = (algToShow as NSString).range(of: "(R U R' U)", options: NSString.CompareOptions.caseInsensitive, range: searchRange)
foundRange4 = (algToShow as NSString).range(of: "(L' U' L U)", options: NSString.CompareOptions.caseInsensitive, range: searchRange) //anti-sexy
foundRange5 = (algToShow as NSString).range(of: "(F R U R' U' F')", options: NSString.CompareOptions.caseInsensitive, range: searchRange) //F-sexy-F'
if foundRange1.location != NSNotFound || foundRange2.location != NSNotFound || foundRange3.location != NSNotFound || foundRange4.location != NSNotFound || foundRange5.location != NSNotFound {
// found an occurrence of the substring! do stuff here
searchRange.location = foundRange1.location + foundRange1.length
mutableAttributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red, range: foundRange1)
searchRange.location = foundRange2.location + foundRange2.length
mutableAttributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.blue, range: foundRange2)
searchRange.location = foundRange3.location + foundRange3.length
mutableAttributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.orange, range: foundRange3)
searchRange.location = foundRange4.location + foundRange4.length
mutableAttributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.brown, range: foundRange4)
searchRange.location = foundRange5.location + foundRange5.length
mutableAttributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red, range: foundRange5)
} else {
// no more substring to find
break
}
}
//Apply
algName!.attributedText = mutableAttributedString;
如您在图像中所见,(R'F R F')的第二个实例不是应该的蓝色。如果我稍微修改一下代码,就可以使它起作用,但是前面(R U R'U)会松开其ORANGE颜色。
我似乎无法使它们两者相互配合工作。