您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 圖文混排入門:UILabel 中插入圖片的三種玩法

編輯:iOS 開發綜合

想在文字之間嵌圖,關鍵類別是 NSTextAttachment。它把圖片包裝成一段可被屬性字串接納的「附件」,再交給 NSAttributedString 渲染。以下三個示範由淺入深。

一、在 Label 中顯示一張圖片

// 圖文混排顯示
- (void)setLabel {
    // NSTextAttachment - 附件
    NSTextAttachment *attachMent = [[NSTextAttachment alloc] init];
    // 為附件設置圖片
    attachMent.image = [UIImage imageNamed:@"d_aini"];
    // 將附件轉為屬性字串
    NSAttributedString *str = [NSAttributedString attributedStringWithAttachment:attachMent];
    // 設置 label 內容
    self.label.backgroundColor = [UIColor grayColor];
    self.label.attributedText = str;
}

顯示效果如下,圖片會以原始尺寸呈現:

二、控制圖片的顯示尺寸

直接塞圖片往往會因為解析度太高而佔掉半個畫面。這時透過 bounds 縮放附件——注意參照基準是文字行高,而不是 Label 的高度,這樣圖片才會和文字視覺對齊。

// 圖文混排控制圖片大小
- (void)setLabel2 {
    NSTextAttachment *attachMent = [[NSTextAttachment alloc] init];
    attachMent.image = [UIImage imageNamed:@"d_aini"];

    // 圖片通常做成正方形,尺寸對齊文字高度
    CGFloat height = self.label.font.lineHeight;
    attachMent.bounds = CGRectMake(0, 0, height, height);

    NSAttributedString *str = [NSAttributedString attributedStringWithAttachment:attachMent];
    self.label.backgroundColor = [UIColor grayColor];
    self.label.attributedText = str;
}

三、把圖片拼接進文字中間

這是最實用的場景,做法是先用附件產生一段屬性字串,再用 NSMutableAttributedString 的 appendAttributedString: 把文字與圖片依序接起來。

// 文字圖片拼接顯示
- (void)setLabel3 {
    // 1. 創建文本附件,並設定 bounds
    NSTextAttachment *attachMent = [[NSTextAttachment alloc] init];
    attachMent.image = [UIImage imageNamed:@"d_aini"];
    CGFloat height = self.label.font.lineHeight;
    attachMent.bounds = CGRectMake(0, 0, height, height);

    // 2. 用附件建立屬性字串
    NSAttributedString *attrString =
        [NSAttributedString attributedStringWithAttachment:attachMent];

    // 3. 建立可變屬性字串並拼接
    NSMutableAttributedString *strM =
        [[NSMutableAttributedString alloc] initWithString:@"米"];
    [strM appendAttributedString:attrString];
    [strM appendAttributedString:[[NSAttributedString alloc] initWithString:@"天天"]];

    self.label.backgroundColor = [UIColor grayColor];
    self.label.attributedText = strM;
}

最終呈現「米🍚天天」這樣的混排效果:

小結:附件負責把圖片變成字串的一員,bounds 負責尺寸,NSMutableAttributedString 負責順序。三者搭配,就能做出 email 內嵌圖標、表情混排這類效果。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved