2012-03-01 20 views
8

सेट करने के लिए TTTAttributedLabel का उपयोग करके मैं आईओएस ऐप बना रहा हूं जिसमें एक लेबल है। मैं दो रंग सेट करना चाहता हूं। शेष भाग के लिए पहले भाग और अन्य रंग के लिए एक।
मैंने प्रवाह पर स्टैक में कुछ संदेश देखे हैं, TTTAttributedLabel में टेक्स्ट में एक से अधिक रंग सेट करने की क्षमता है। मेरा टेक्स्ट "एबीसी> डीफ़" जैसा होगा। "एबीसी" के लिए, मैं भूरा रंग सेट करना चाहता हूं और "डीफ़" के लिए, मैं सफेद रंग सेट करना चाहता हूं।
मैं इसे कैसे सेट कर सकता हूं?आईओएस - दो रंग टेक्स्ट

उत्तर

16
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 

जो आपकी स्ट्रिंग में "def" की खोज करता है और टेक्स्ट के अग्रभूमि रंग को उस सीमा के लिए सफेद पर सेट करता है। उम्मीद है की यह मदद करेगा। मैंने अभी कल ही यह सीखा। अपने प्रश्न के दौरान इसे समझने की कोशिश करते हुए अपने प्रश्न में आया।

+0

ब्लॉक के अंत में mutableAttributedString को वापस करने के लिए मत भूलना। – djibouti33

+0

@ djibouti33 धन्यवाद, मुझे नहीं पता कि मुझे यह कैसे याद आया। अब उसमें शामिल करने के लिए उत्तर संपादित किया। – DonnaLea

6

आप TTTRegexAttributedLabel का उपयोग यहां उपलब्ध कर सकते हैं: https://github.com/kwent/TTTRegexAttributedLabel। (TTTAttributed लेबल आधारित है लेकिन नियमित अभिव्यक्तियों के साथ उपयोग करना अधिक आसान है)

//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]]; 
+4

उत्तर देने के लिए धन्यवाद। मेरी समस्या TTTAttributedLabel का उपयोग कर हल हो गई। भविष्य में, मैंने आपके द्वारा सुझाए गए लाइब्रेरी का उपयोग करने के लिए ध्यान में रखा होगा। – Satyam

संबंधित मुद्दे