如何在UILabel文字的前后添加圖片?


現在遇到這樣一個需求:Lable中顯示的文字需要用一個引號來括住

這個時候需要借助Label的Attributstring中textAttachment,需要在文字中的哪個部位放置圖片,我們就將該文字從哪段切開,然后在末尾添加圖片(如果要在開頭添加,只需要拼接一段" "在末尾添加上圖片即可),具體的代碼實現如下:

- (void)insertPictureInLabel
{
    
    NSTextAttachment *foreAttachment = [[NSTextAttachment alloc]init];
    foreAttachment.image = [UIImage imageNamed:@"bl_ios_splb_qyh"];
    foreAttachment.bounds = CGRectMake(0, 0, 15, 15);
    
    NSTextAttachment *backAttachment = [[NSTextAttachment alloc]init];
    backAttachment.image = [UIImage imageNamed:@"bl_ios_splb_hyh"];
    backAttachment.bounds = CGRectMake(0, 0, 15, 15);
    
    NSMutableAttributedString *orginalAttributString = [[NSMutableAttributedString alloc]initWithString:@""];
    NSAttributedString *firsString = [NSAttributedString attributedStringWithAttachment:foreAttachment];
    [orginalAttributString appendAttributedString:firsString];
    
    UILabel *pictureLabel = [[UILabel alloc]initWithFrame:CGRectMake(50, 64, screenSize.width - 100, 150)];
    pictureLabel.backgroundColor = [UIColor clearColor];
    NSMutableAttributedString *newAttributString = [[NSMutableAttributedString alloc]initWithString:@" 現在說的一些可能比較基礎,大家會比較沒興趣,可是基礎是練成高超技術的基石,趁着寫博客的時候我自己也回顧一下這些基礎知識,如果需要的demo的話我再發上來 "];
    pictureLabel.font = [UIFont systemFontOfSize:15];
    pictureLabel.numberOfLines = 0;
    NSAttributedString *secondString = [NSAttributedString attributedStringWithAttachment:backAttachment];
    [newAttributString appendAttributedString:secondString];
    
    [orginalAttributString appendAttributedString:newAttributString];
    pictureLabel.attributedText = orginalAttributString;
    
    [self.view addSubview:pictureLabel];
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM