1. 程式人生 > >利用NSAttributeString進行圖文混編

利用NSAttributeString進行圖文混編

    NSString* showText = [NSString stringWithFormat:@"%@%@",text1,text2];
    NSRange range1 = [showText rangeOfString:text1];
    NSRange range2 = [showText rangeOfString:text2];

    NSDictionary* attributes1 = @{
                                 NSFontAttributeName: font,
                                 NSForegroundColorAttributeName:dColor
                                 };
    NSDictionary
* attributes2 = @{ NSFontAttributeName: font, NSForegroundColorAttributeName:cColor }; NSMutableAttributedString* attributeString = [[[NSMutableAttributedString alloc] initWithString:showText] autorelease]; [attributeString addAttributes:attributes1 range:range1]; [attributeString addAttributes:attributes2 range:range2]; NSTextAttachment* textAttachment = [[[NSTextAttachment alloc] init] autorelease]; textAttachment.image
= image; textAttachment.bounds = CGRectMake(0, -4, 16, 16); // 微調圖片位置 NSAttributedString* imageAttachment = [NSAttributedString attributedStringWithAttachment:textAttachment]; [attributeString insertAttributedString:imageAttachment atIndex:range1.length]; // 插入圖片 label.attributedText = attributeString;