Tworzę aplikację na iOS z etykietą. Chcę ustawić dwa kolory. Jeden dla pierwszej części i inny kolor dla pozostałej części.
Widziałem kilka wiadomości w Stack overflow, które TTTAttributedLabel mają możliwość ustawienia więcej niż jednego koloru tekst. Mój tekst będzie wyglądał jak „ABC > def”. Dla "ABC" chcę ustawić kolor brązowy, a dla "def" chcę ustawić kolor biały.
Jak mogę to ustawić?
2 odpowiedzi
NSString* text = @"ABC > def";
attributedLabel = [[[TTTAttributedLabel alloc] initWithFrame:frame] autorelease];
attributedLabel.numberOfLines = 0;
attributedLabel.lineBreakMode = UILineBreakModeWordWrap;
attributedLabel.fontColor = [UIColor brownColor];
[attributedLabel setText:text afterInheritingLabelAttributesAndConfiguringWithBlock:^(NSMutableAttributedString *mutableAttributedString) {
NSRange whiteRange = [text rangeOfString:@"def"];
if (whiteRange.location != NSNotFound) {
// Core Text APIs use C functions without a direct bridge to UIFont. See Apple's "Core Text Programming Guide" to learn how to configure string attributes.
[mutableAttributedString addAttribute:(NSString *)kCTForegroundColorAttributeName value:(id)[UIColor whiteColor].CGColor range:whiteRange];
}
return mutableAttributedString;
}];
[attributedLabel sizeToFit]; //this may not be needed if the frame provided is large enough
To wyszukuje „def” w ciągu i ustawia kolor pierwszego planu tekstu na biały dla tego zakresu. Mam nadzieję że to pomoże. Dopiero wczoraj się tego dowiedziałem. Natknąłem się na twoje pytanie, próbując to rozgryźć dla siebie.
Możesz użyć TTTRegexAttributedLabel dostępnego pod adresem: https://github.com/kwent/TTTRegexAttributedLabel. (Oparty na TTTattributedLabel, ale łatwiejszy w użyciu z wyrażeniami regularnymi)
//SET FONT ONLY ON FIRST MATCH REGEX
TTTRegexAttributedLabel *label = [[TTTRegexAttributedLabel alloc] init];
label.textColor = [UIColor whiteColor];
NSString *s = @"ABC > def";
[self.label setText:s withFirstMatchRegex:@"^[a-zA-Z ]*>"
withFont:[UIFont systemFontOfSize:12]
withColor:[UIColor brownColor]];
Podobne pytania
Nowe pytania
ios
iOS to mobilny system operacyjny działający na urządzeniach Apple iPhone, iPod touch i iPad. Użyj tego tagu [ios] w przypadku pytań związanych z programowaniem na platformie iOS. Użyj powiązanych tagów [objective-c] i [swift] w przypadku problemów specyficznych dla tych języków programowania.