iOS開發富文本製做 圖片和文字/NSMutableParagraphStyle/NSMutableAttributedString

/NSMutableParagraphStyle/NSMutableAttributedString 組合使html

 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 \n同義詞 GTR(日產公司生產的高性能汽車)通常指日產GT-R\n在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:@"\n2017年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];

 

 

一、 在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那兩句刪除後,文字能夠正常顯示。我記得我以前是這樣寫,能夠同時顯示 xcode

 

圖片在上 文字在下 微信

  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)];//圖片距離右邊框距離減小圖片的寬度,其它不邊 

 

二、在UILabel上製做app

在實際項目開發過程當中,咱們常會遇到一段文字中既要有圖片又要有文字,例如咱們常用的QQ、微信的聊天對話框中,表情和文字共存就是一種典型的圖文混排。框架


QQ20150827-1.png


能夠直接使用Quart2D,直接在Label的draw方法中畫圖片上去,可是這種方法成本比較高,咱們推薦使用text自帶的屬性來作。性能

要作到圖中在文字中插入表情的效果,首先咱們得來了解一下一個叫富文本的東西。所謂富文本,個人理解就是一個豐富多彩的文本,多彩體如今能夠在一個text中顯示出不一樣的文字,加入一些色彩豐富的圖片,但它能作到的還能夠修改不一樣文字的字體加入下劃線,豐富多采。字體


QQ20150827-2.png


咱們都知道label有text這個文本屬性,要作到富文本效果,就須要用到一個並非全部人都知道的富文本屬性 attributedText(textView、textField中都有這個屬性)url

1.修改文字的樣式

步驟以下:spa

  • 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的話我再發上來。

 

1、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

 

1、框架中的原始定義以下:

@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;       //英文斷字連字符

 

2、NSTextAlignment文字對齊方式枚舉(IOS6以上有效):

NSTextAlignmentLeft       //居左

NSTextAlignmentRight      //居右

NSTextAlignmentCenter     //居中

NSTextAlignmentNatural    //默認

NSTextAlignmentJustified  //自調整

 

3、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];

相關文章
相關標籤/搜索