Versuchen Sie dies, Ihre attributierte Zeichenfolge hat keinen Wert, wenn Sie versuchen, den Bereich der Zeichenfolge zu erhalten. Sie müssen der attributierten Zeichenfolge vorher einen Zeichenfolgenwert geben. Sie
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)
Oder Sie können eine Erweiterung von UILabel tun.
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
}
Um es zu verwenden.
self.testLabel.colorString(text: "mehmet alper tabak",
coloredText: "alper")
Bitte senden Sie Ihren Code als Text, nicht als Bild. Sie können Code aus einem Bild nicht suchen oder referenzieren. – rmaddy
@maddy mein schlecht, sorry. – Alper