我想做一个像这样的NSString通知:“你必须支付4.00美元。”。钱有红色。在Android中,我可以使用HTML.formhtml做。但我不知道该怎么做它在IOS.Who可以帮助我?
答案 0 :(得分:2)
试试这段代码
CATextLayer *aTextLayer_= [[[CATextLayer alloc]init] autorelease];
aTextLayer_.frame = CGRectMake(10, 100, 300, 50);
aTextLayer_.backgroundColor=[UIColor clearColor].CGColor;
aTextLayer_.foregroundColor = [[UIColor redColor] CGColor];
aTextLayer_.alignmentMode=kCAAlignmentCenter;
aTextLayer_.contentsScale = [[UIScreen mainScreen] scale];
aTextLayer_ .wrapped=YES;
[aTextLayer_ setAlignmentMode:kCAAlignmentLeft];
UIFont *smallFont = [UIFont systemFontOfSize:25];
CTFontRef ctSmallFont = CTFontCreateWithName((CFStringRef)smallFont.fontName, smallFont.pointSize, NULL);
UIFont *boldFont = [UIFont systemFontOfSize:25];
CTFontRef ctBoldFont = CTFontCreateWithName((CFStringRef)boldFont.fontName, boldFont.pointSize, NULL);
CGColorRef cgColor = [UIColor greenColor].CGColor;
CGColorRef cgColor1 = [UIColor redColor].CGColor;
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
(id)ctSmallFont, (id)kCTFontAttributeName,
cgColor, (id)kCTForegroundColorAttributeName, nil];
NSDictionary *subattributes = [NSDictionary dictionaryWithObjectsAndKeys:
(id)ctBoldFont, (id)kCTFontAttributeName,
cgColor1, (id)kCTForegroundColorAttributeName, nil];
CFRelease(ctBoldFont);
NSString *subString=@"You must pay 4.00 dollar.";
NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:subString attributes:attributes];
[attrStr addAttributes:subattributes range:NSMakeRange(13,4)];
aTextLayer_.string=attrStr;
[self.view.layer addSublayer:aTextLayer_];
答案 1 :(得分:1)
如果您不想使用UIWebView
,则最佳选择是使用NSAttributedString
。
一个天真的实现,没有太多关于角落案例和错误检查,就像
NSString * string = @"You must pay 4.00 dollar";
NSString * pattern = @"You must pay (.+) dollar";
NSRegularExpression * regex = [[NSRegularExpression alloc] initWithPattern:pattern options:0 error:NULL];
NSArray * matches = [regex matchesInString:string options:0 range:NSMakeRange(0, string.length)];
NSRange priceRange = [matches[0] rangeAtIndex:1];
NSMutableAttributedString * attrString = [[NSMutableAttributedString alloc] initWithString:string];
[attrString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:priceRange];
请注意,我假设您的模式始终为You must pay (.+) dollar
。如果它不同,只需调整正则表达式,以便检索需要风格化的子字符串的NSRange
。
然后,您可以将属性字符串用作接受NSAttributedString
的任何内容,例如UILabel
自iOS 6起具有attributedText
属性,因此您可以执行类似
yourLabel.attributedText = attrString;
答案 2 :(得分:0)
您可以将HTML代码添加到UIWebView
[_webView loadHTMLString:@"<p>You must pay <font color=\"red\">4.00</font> dollar. </p> " baseURL:nil];
试试这段代码
----------------- Alternate Option ----------------------------
如果要修复此文本格式(您必须支付XXXX.XXX美元。)更好创建自定义组件