如何在iphone中突出显示选定的文本/字符串

如何在iphone中突出显示选定的文本/字符串,iphone,ios,objective-c,text,Iphone,Ios,Objective C,Text,我有一个字符串“Expert Sales Manager”作为手机标题,我只想突出显示iphone手机标题中的“Sales”。 请为我推荐一种方法。对于ios 6或更高版本,您可以使用nsmutableAttributeString NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:@"OneTwoThreeFour"]; [string addAttribu

我有一个字符串“Expert Sales Manager”作为手机标题,我只想突出显示iphone手机标题中的“Sales”。

请为我推荐一种方法。

对于ios 6或更高版本,您可以使用
nsmutableAttributeString

   NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:@"OneTwoThreeFour"];
    [string addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Helvetica-Bold" size:20] range:NSMakeRange(3,5)];
并将属性文本设置为元素

label.attributedText = string;

由于iOS 6,UIKit支持绘制属性字符串

UILabel

@property(nonatomic, copy) NSAttributedString *attributedText;
您只需要建立
NSAttributedString
。基本上有两种方式:

  • 附加具有相同属性的文本块-为每个部分创建一个
    NSAttributedString
    实例,并将它们附加到一个
    NSMutableAttributedString

  • NSString *infoString=@"This is an example of Attributed String";
    NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:infoString];
    NSInteger _stringLength=[infoString length];
    
    UIColor *_black=[UIColor blackColor];
    UIFont *font=[UIFont fontWithName:@"Helvetica-Bold" size:30.0f];
    [attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, _stringLength)];
    [attString addAttribute:NSForegroundColorAttributeName value:_black range:NSMakeRange(0, _stringLength)];
    
  • 从纯字符串创建属性文本,然后为给定范围添加属性–找到数字(或任何数字)的范围,并对其应用不同的突出显示属性


  • 您可以使用
    nsmutableAttributeString

    NSString *infoString=@"This is an example of Attributed String";
    NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:infoString];
    NSInteger _stringLength=[infoString length];
    
    UIColor *_black=[UIColor blackColor];
    UIFont *font=[UIFont fontWithName:@"Helvetica-Bold" size:30.0f];
    [attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, _stringLength)];
    [attString addAttribute:NSForegroundColorAttributeName value:_black range:NSMakeRange(0, _stringLength)];
    

    是否要将粗体属性添加到sales?是的,我希望将粗体属性添加到sales(仅限)。因此,您可以使用属性字符串而不是
    NSString
    ,并查找sales字符的范围。或者,您可以在属性字符串中键入Expert Sales Manager作为Expert Sales Manager。希望这能解决你的问题。