程序员iOS Developer

iOS NSMutableAttributedString 常用

2017-04-24  本文已影响111人  Zhui_Do

NSMutableAttributedString 常用的Attributes

      UITextView *textView = [[UITextView alloc]initWithFrame:(CGRectMake(0, 0, HSWidth, HSHeight))];
    
    textView.delegate = self;
    textView.backgroundColor = [UIColor redColor];
    [self.view addSubview:textView];
    
    textView.text = @"哈哈哈哈哈哈哈哈哈helloo哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈";
    NSMutableAttributedString*attributeString_atts=[[NSMutableAttributedString alloc]initWithString: @"哈哈哈哈哈哈哈哈哈helloo哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈"];
    //背景色
    UIColor  *backgroundColor=[UIColor whiteColor];
    //字体
    UIFont *font=[UIFont fontWithName:@"STHeitiSC-Light" size:28.0];
    //偏移量
    NSNumber *baseLineOffset=[NSNumber numberWithFloat:10.0];
    //文本颜色
    UIColor  *foregroundColor=[UIColor blackColor];
    //字间距
    NSNumber *kern=[NSNumber numberWithFloat:1.5];
    //连体字
    NSNumber *ligature=[NSNumber numberWithFloat:0];
    //超链接文本
    NSURL    *linkURL=[NSURL URLWithString:@"http://www.baidu.com"];
    //删除线格式
    NSNumber *strikeLine=[NSNumber numberWithInt:NSUnderlineStyleSingle];
    //下划线格式
    NSNumber *underLine=[NSNumber numberWithInt:NSUnderlineStyleDouble];
    //段落格式 段落中有更多段落的格式
    NSMutableParagraphStyle *paragraphStyle=[[NSMutableParagraphStyle alloc]init];//新起行缩进
    [paragraphStyle setHeadIndent:10.0];
    //首行缩进
    [paragraphStyle setFirstLineHeadIndent:21.0];
    //行高倍数因子
    [paragraphStyle setLineHeightMultiple:1.3];
    //行间距
    [paragraphStyle setLineSpacing:10.0];
    //上述两属性说明:行间距是每行之间距离,计算高度时,可能出现偏差;行高倍数因子,行高固定。
    
    //断行 默认按单词
    paragraphStyle.lineBreakMode=NSLineBreakByWordWrapping;
    [paragraphStyle setTailIndent:375.0];
    
    NSDictionary *attrsDic=@{
                             NSForegroundColorAttributeName:foregroundColor,
                             NSBackgroundColorAttributeName:backgroundColor,
                             NSBaselineOffsetAttributeName:baseLineOffset,
                             NSFontAttributeName:font,
                             NSKernAttributeName:kern,
                             NSLigatureAttributeName:ligature,
                             NSLinkAttributeName:linkURL,
                             NSUnderlineStyleAttributeName:underLine,
                             NSStrikethroughStyleAttributeName:strikeLine,
                             NSParagraphStyleAttributeName:paragraphStyle
                             };
    
    //全文使用
    [attributeString_atts addAttributes:attrsDic range:NSMakeRange(0, [@"哈哈哈哈哈哈哈哈哈helloo哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈" length])];
    textView.attributedText = attributeString_atts;
    textView.userInteractionEnabled = YES;
    textView.editable = false;

设置UITextViewDelegate

-(BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange interaction:(UITextItemInteraction)interaction
{
    return YES;
}
效果图.png
上一篇下一篇

猜你喜欢

热点阅读