iOS开发富文本制作 图片和文字/NSMutableParagraphStyle/NSMutableAttributedString

/NSMutableParagraphStyle/NSMutableAttributedString 组合使

 NSString * titlestr=@"日产GT-R";
    NSMutableParagraphStyle * paragraphstyle0 =[[NSMutableParagraphStyle alloc]init];
    [paragraphstyle0 setLineSpacing:47];
    paragraphstyle0.alignment = NSTextAlignmentCenter;
    
    NSMutableAttributedString * attribustring0 =[[NSMutableAttributedString alloc]initWithString: titlestr attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:35],NSForegroundColorAttributeName:[UIColor blueColor],NSParagraphStyleAttributeName:paragraphstyle0}];
    
    
    UITextView * textview =[[UITextView alloc]initWithFrame:CGRectMake(28, 64, self.view.frame.size.width-56, self.view.frame.size.height-90)];
    
    textview.textColor =[UIColor blackColor];
    textview.scrollEnabled = YES;
    textview.editable = NO;
    
    NSString * text= @"日产GT-R 
同义词 GTR(日产公司生产的高性能汽车)一般指日产GT-R
在20世纪60年代的汽车普遍不能胜任长途旅行的工作,机械可靠程度很低,由此,出现了一批高性能高可靠性的大马力跑车,被称为GT。2015年米其林助力日产GT-R赛车夺得Super GT/GT500组别桂冠。[1]  人类汽车历史上只要是能被称为GT的车型,必不是流俗之辈。1957年,SKYLINE车系诞生于一个名为“王子”的车厂,由于车厂经营不善,在1969年的时候被日产汽车收购。收购王子后的日产汽车为了和走在前面的丰田等车厂竞争,急需几款外观以及性能都同样出众的车型来提升品牌价值和市场占有率。于是,重组后一直被搁置的Skyline(天际线)和SILVIA等车型被正式批准生产。GT-R系列的荣光之路就此开始。";
    
    //行间距
    NSMutableParagraphStyle * paragraphstyle =[[NSMutableParagraphStyle alloc]init];
    [paragraphstyle setLineSpacing:13];
    paragraphstyle.alignment = NSTextAlignmentLeft;
    
    NSMutableAttributedString * attribustring =[[NSMutableAttributedString alloc]initWithString: text attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:26],NSForegroundColorAttributeName:[UIColor blackColor],NSParagraphStyleAttributeName:paragraphstyle}];
    
    
    NSMutableParagraphStyle * paragraphstyle2 =[[NSMutableParagraphStyle alloc]init];
    [paragraphstyle2 setLineSpacing:13];
    paragraphstyle2.alignment = NSTextAlignmentRight;
    
    NSAttributedString * attribustring2 =[[NSAttributedString alloc]initWithString:@"
2017年03月01日" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:26],NSForegroundColorAttributeName:[UIColor blackColor],NSParagraphStyleAttributeName:paragraphstyle2}];
    
    //合并
    [attribustring appendAttributedString:attribustring2];
    [attribustring0 appendAttributedString:attribustring];
    textview.attributedText =attribustring0;
    
    [self.view addSubview:textview];

1、 在UIButton上制作

[button setTitle:@"设为默认" forState:UIControlStateNormal];
        [button setTitle:@"默认地址" forState:UIControlStateSelected];
        [button setImage:[UIImage imageNamed:@"weixuanzhong"] forState:UIControlStateNormal];
        [button setImage:[UIImage imageNamed:@"xuanzhong"] forState:UIControlStateSelected];
[button setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 80)];
        [button setTitleEdgeInsets:UIEdgeInsetsMake(0, 20, 0, 0)];
这样应该可以同时显示吧,图片在左文字在右,可是只显示图片,当我把setimage那两句删除后,文字可以正常显示。我记得我之前是这样写,可以同时显示 

图片在上 文字在下 

  1. btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;//使图片和文字水平居中显示  
  2.     [btn setTitleEdgeInsets:UIEdgeInsetsMake(btn.imageView.frame.size.height ,-btn.imageView.frame.size.width, 0.0,0.0)];//文字距离上边框的距离增加imageView的高度,距离左边框减少imageView的宽度,距离下边框和右边框距离不变  
  3.     [btn setImageEdgeInsets:UIEdgeInsetsMake(0.0, 0.0,0.0, -btn.titleLabel.bounds.size.width)];//图片距离右边框距离减少图片的宽度,其它不边 

2、在UILabel上制作

在实际项目开发过程中,我们常会遇到一段文字中既要有图片又要有文字,例如我们经常使用的QQ、微信的聊天对话框中,表情和文字共存就是一种典型的图文混排。


QQ20150827-1.png


可以直接使用Quart2D,直接在Label的draw方法中画图片上去,但是这种方法成本比较高,我们推荐使用text自带的属性来做。

要做到图中在文字中插入表情的效果,首先我们得来了解一下一个叫富文本的东西。所谓富文本,我的理解就是一个丰富多彩的文本,多彩体现在可以在一个text中显示出不同的文字,加入一些色彩丰富的图片,但它能做到的还可以修改不同文字的字体加入下划线,丰富多采。


QQ20150827-2.png


我们都知道label有text这个文本属性,要做到富文本效果,就需要用到一个并不是所有人都知道的富文本属性 attributedText(textView、textField中都有这个属性)

1.修改文字的样式

步骤如下:

  • NSMutableAttributedString 创建一个富文本对象
  • 调用富文本的对象方法 addAttribute:(NSString * )value:(id) range:(NSRange) 来修改对应range范围中 attribute属性的 value值
      // 创建一个富文本
    NSMutableAttributedString *attri =     [[NSMutableAttributedString alloc] initWithString:@"哈哈哈哈哈123456789"];

    // 修改富文本中的不同文字的样式
    [attri addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0, 5)];
    [attri addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] range:NSMakeRange(0, 5)];

    // 设置数字为红色
    [attri addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(5, 9)];
    [attri addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:30] range:NSMakeRange(5, 9)];

在这段代码中,分别设置了range为(0,5)的文字,也就是哈哈哈哈哈为font20号字体大小,颜色为蓝色的样式;设置了range为(6,9)也就是123456789为font30号字体大小,颜色为红色样式

2.文字中添加图片

步骤如下:

  • 创建NSTextAttachment的对象,用来装在图片
  • 将NSTextAttachment对象的image属性设置为想要使用的图片
  • 设置NSTextAttachment对象bounds大小,也就是要显示的图片的大小
  • 用[NSAttributedString attributedStringWithAttachment:attch]方法,将图片添加到富文本上

      // 添加表情
      NSTextAttachment *attch = [[NSTextAttachment alloc] init];
      // 表情图片
          attch.image = [UIImage imageNamed:@"d_aini"];
      // 设置图片大小
          attch.bounds = CGRectMake(0, 0, 32, 32);
    
      // 创建带有图片的富文本
          NSAttributedString *string = [NSAttributedString attributedStringWithAttachment:attch];
      [attri appendAttributedString:string];
    
      // 用label的attributedText属性来使用富文本
      self.textLabel.attributedText = attri;

现在说的一些可能比较基础,大家会比较没兴趣,可是基础是练成高超技术的基石,趁着写博客的时候我自己也回顾一下这些基础知识,如果需要的demo的话我再发上来。

一、NSMutableAttributedString 类的部分常用方法

复制代码
复制代码
// 在一定范围中添加单个文字属性
// 参数1:字符属性名
// 参数2:属性值
// 参数3:范围
- (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range;

// 在一定范围中使用字典添加多个文字属性
// 参数1:属性字典
// 参数2:范围
- (void)addAttributes:(NSDictionary<NSString *, id> *)attrs range:(NSRange)range;

// 在一定范围中删除文字具有的某个文字属性
// 参数1:字符属性名
// 参数2:范围
- (void)removeAttribute:(NSString *)name range:(NSRange)range;

// 在一定范围中替换字符串
// 参数1:范围
// 参数2:要替换的字符串
- (void)replaceCharactersInRange:(NSRange)range withAttributedString:(NSAttributedString *)attrString;

// 在对应的角标处插入富文本
// 参数1:要插入的字符串
// 参数2:要插入的角标位置
- (void)insertAttributedString:(NSAttributedString *)attrString atIndex:(NSUInteger)loc;

// 将某个富文本拼接到后面
// 参数:要拼接的字符串
- (void)appendAttributedString:(NSAttributedString *)attrString;

// 删除一定范围中的字符
// 参数:范围
- (void)deleteCharactersInRange:(NSRange)range;

// 将字符串全部置换为另一个富文本字符串
// 参数:置换后的富文本字符串
- (void)setAttributedString:(NSAttributedString *)attrString;

Foundation-几种段落排版格式NSMutableParagraphStyle

 

一、框架中的原始定义如下:

@property(readwrite) CGFloat lineSpacing;           //行间距

@property(readwrite) CGFloat paragraphSpacing;      //段落间距

@property(readwrite) NSTextAlignment alignment;     //文字对齐格式

@property(readwrite) CGFloat firstLineHeadIndent;   //首行缩进

@property(readwrite) CGFloat headIndent;            //行首缩进

@property(readwrite) CGFloat tailIndent;            //行尾缩进

@property(readwrite) NSLineBreakMode lineBreakMode; //段落文字溢出隐藏方式

@property(readwrite) CGFloat minimumLineHeight;     //最小行高

@property(readwrite) CGFloat maximumLineHeight;     //最大行高

@property(readwrite) NSWritingDirection baseWritingDirection;//段落书写方向

@property(readwrite) CGFloat lineHeightMultiple;    //多行行高

@property(readwrite) CGFloat paragraphSpacingBefore;//段落前间距

@property(readwrite) float hyphenationFactor;       //英文断字连字符

 

二、NSTextAlignment文字对齐方式枚举(IOS6以上有效):

NSTextAlignmentLeft       //居左

NSTextAlignmentRight      //居右

NSTextAlignmentCenter     //居中

NSTextAlignmentNatural    //默认

NSTextAlignmentJustified  //自调整

三、NSWritingDirection文字书写方向(IOS6以上有效):

NSWritingDirectionNatural      //使用Bidi算法规则P2和P3定义方向

NSWritingDirectionLeftToRight  //从左向右

NSWritingDirectionRightToLeft  //从右向左

 

示例源码:

Foundation-几种段落排版格式NSMutableParagraphStyle

 

    NSString *text = @"秋叶黄,秋叶黄,我深深的沉醉其中,摇摆的叶片,枯黄着也是秋天,飘落着也是秋天;秋叶黄,秋叶黄,你随风悄悄的散去,枯萎的树枝,下着雨也是秋天,吹着风也是秋天.";

   

    // 就用这两个options枚举参数吧,我也不知道为啥

    NSStringDrawingOptions options = NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading;

    // labelW是段落的固定宽度;CGFLOAT_MAX固定用这个;attributes按照下面的语句fontSize是字体的大小

    // >IOS7

    CGFloat labelH = [text boundingRectWithSize:CGSizeMake(labelW, CGFLOAT_MAX) options:options attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]} context:nil].size.height;

    //

    //CGFloat labelH = [text sizeWithFont:[UIFont systemFontOfSize:fontSize] constrainedToSize:CGSizeMake(labelW, CGFLOAT_MAX)].height;

    // 打印计算的高度看一下

    NSLog(@"文字段落高度为:%f",labelH);

    //实际行数

    NSInteger lineNum = labelH/fontSize;

   

    NSMutableParagraphStyle *paragraphStyle = [[ NSMutableParagraphStyle alloc ] init];

    //文字对齐方式

    paragraphStyle.alignment = NSTextAlignmentJustified;

    //段落首字符缩进两个字

    paragraphStyle.firstLineHeadIndent = 2*fontSize;

    //行间距

    paragraphStyle.lineSpacing = lingSpace;

    //属性字典,包括前景字体颜色和段落属性

    NSDictionary *attributes = @{NSForegroundColorAttributeName:[UIColor redColor],NSParagraphStyleAttributeName:paragraphStyle};

    //属性字符串

    NSAttributedString *attributedText = [[ NSAttributedString alloc ] initWithString : text attributes :attributes];

   

    UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 70, 300, labelH+lineNum*lingSpace)];

    // 文字行数设置为0

    label1.numberOfLines = 0;

    // label背景色

    label1.backgroundColor = [UIColor greenColor];

    label1.attributedText = attributedText;

    // 显示label

 

    [self.view addSubview:label1];

原文地址:https://www.cnblogs.com/xujiahui/p/6526629.html