The text of the label in ios is displayed in multiple colors.

Source: Internet
Author: User

The text of the label in ios is displayed in multiple colors.

1. In the initialization method, add all labels with the keywords to be highlighted to the labels array and add the colors of these labels in the original font to labelTextColors. The Code is as follows:

Self. labels = [NSArray arrayWithObjects: self. textLabel, self. detailTextLabel, nil];

Self. labelTextColors = [NSArray arrayWithObjects: kColor_Black, kColor_LightGray, nil];

Ii. Add this code in layoutSubviews

For (int I = 0; I <self. labels. count; I ++ ){

UILabel * label = self. labels [I];

// 1. Retrieve the color of the original label font.

UIColor * originalColor = self. labelTextColors [I];

// 2. restore the original color

NSMutableAttributedString * originalMat = label. attributedText. mutableCopy;

[OriginalMat setAttributes: @ {NSForegroundColorAttributeName: originalColor}

Range: [label. text rangeOfString: label. text];

Label. attributedText = originalMat;

// 3. Highlight keywords

NSMutableAttributedString * mat = label. attributedText. mutableCopy;

[Mat setAttributes: @ {NSForegroundColorAttributeName: [UIColor blueColor]}

Range: [label. text rangeOfString: self. keyWords]; // keyWords are the keyWords to be highlighted.

Label. attributedText = mat;

}

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.