最基本的標籤使用只能讓同一字串有著同樣的屬性,那麼我想要有多重文字屬性 (Multiple Text Attribute)該怎麼做?比如字體有大有小,又如顏色有紅有黃,再如上標和下標等等,這一切都已經能實現了!
其實只要使用AttributedString就能同時塞入多種屬性,記得匯入<CoreText/CTStringAttributes.h>才能使用喔!
/** Theme: Multiple Text Attribute IDE: Xcode 5 Language: Objective C Date: 103/05/26 Author: HappyMan Blog: https://cg2010studio.wordpress.com/ */ #import &amp;amp;amp;amp;amp;amp;amp;amp;lt;CoreText/CTStringAttributes.h&amp;amp;amp;amp;amp;amp;amp;amp;gt; - (void)viewDidLoad { [super viewDidLoad]; UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 100, 200, 80)]; NSString *infoString = @"我是快樂測試人 歡迎來逍遙文工作室"; NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:infoString]; // 上標 [attString addAttribute:(NSString *)kCTSuperscriptAttributeName value:@1 range:NSMakeRange(2, 2)]; // 下標 [attString addAttribute:(NSString *)kCTSuperscriptAttributeName value:@-1 range:NSMakeRange(8, 2)]; // 字體 UIFont *font = [UIFont fontWithName:@"Avenir-Light" size:24]; [attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(11, 6)]; // 顏色 UIColor *color = [UIColor whiteColor]; [attString addAttribute:NSForegroundColorAttributeName value:color range:NSMakeRange(11, 3)]; label.attributedText = attString; [label sizeToFit]; [self.view addSubview:label]; }編譯執行後的結果你在文章頂端就已經看過囉!
2022/06/30 更新
TextView 也是可以讓文字變得花俏~這次是想讓某些字可以變成連結可點擊,且文字下要有底線~
[str addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:NSMakeRange(8, 5)]; [str addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:NSMakeRange(16, 5)]; [str addAttribute:NSUnderlineColorAttributeName value:[UIColor blackColor] range:NSMakeRange(8, 5)]; [str addAttribute:NSUnderlineColorAttributeName value:[UIColor blackColor] range:NSMakeRange(16, 5)]; [str addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(8, 5)]; [str addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(16, 5)];&amp;amp;amp;lt;/pre&amp;amp;amp;gt; self.agreementTextView.attributedText = str; // 連結想要可點擊卻不要可選取 #pragma mark - UITextViewDelegate - (void)textViewDidChangeSelection:(UITextView *)textView { if (textView == self.agreementTextView &amp;&amp; textView.selectedTextRange != nil) { // `selectable` is required for tappable links but we do not want // regular text selection, so clear the selection immediately. textView.delegate = nil;//Disable delegate while we update the selectedTextRange otherwise this method will get called again, circularly, on some architectures (e.g. iPhone7 sim) textView.selectedTextRange = nil;//clear selection, will happen before copy/paste/etc GUI renders textView.delegate = self;//Re-enable delegate } }參考:
Comments on: "[iOS] 多重文字屬性 (Multiple Text Attribute)" (3)
這次換加密 App 用上!需要連結與底線~
讚讚
此刻製作地球與天堂App,很高興直接用上! 😉
讚讚
[…] 此外,可參考先前介紹的文章:多重文字屬性 (Multiple Text Attribute)、LABEL裡的行距、LABEL裡的字距。 […]
讚讚