小智 7
试试这个,当你尝试获取字符串的范围时,你的属性字符串没有值.在此之前,您必须为属性字符串赋予字符串值.您
let descriptionLabel: UILabel = {
let label = UILabel()
// String variable containing the text.
let fullString = "mehmet alper tabak"
// Choose wwhat you want to be colored.
let coloredString = "alper"
// Get the range of the colored string.
let rangeOfColoredString = (fullString as NSString).range(of: coloredString)
// Create the attributedString.
let attributedString = NSMutableAttributedString(string:fullString)
attributedString.setAttributes([NSForegroundColorAttributeName: UIColor.red],
range: rangeOfColoredString)
label.attributedText = attributedString
return label
}()
descriptionLabel.frame = CGRect(x: 50, y: 50, width: 140, height: 100)
self.view.addSubview(descriptionLabel)
Run Code Online (Sandbox Code Playgroud)
或者你可以扩展UILabel.
extension UILabel {
func colorString(text: String?, coloredText: String?, color: UIColor? = .red) {
let attributedString = NSMutableAttributedString(string: text!)
let range = (text! as NSString).range(of: coloredText!)
attributedString.setAttributes([NSForegroundColorAttributeName: color!],
range: range)
self.attributedText = attributedString
}
Run Code Online (Sandbox Code Playgroud)
使用它.
self.testLabel.colorString(text: "mehmet alper tabak",
coloredText: "alper")
Run Code Online (Sandbox Code Playgroud)