iOS-圖文混排方案-2種方案

ios的圖文混排有兩種方案
1.使用NSTextAttachment

- (NSMutableAttributedString*)createTextImage:(NSString*)text witImage:(NSString*)imageName{
    NSMutableAttributedString *scaleStr=  [[NSMutableAttributedString alloc] initWithString:text attributes:@{NSForegroundColorAttributeName:[UIColor whiteColor], NSFontAttributeName:PingFangBold(18)}];
   //添加圖片
    NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init];
    textAttachment.bounds = CGRectMake(0, 2, 12, 7); //根據(jù)圖片位置進行調(diào)整
    textAttachment.image = [UIImage imageNamed:imageName];
    NSAttributedString *attributedImage = [NSAttributedString attributedStringWithAttachment:(NSTextAttachment *)(textAttachment)];
   //圖片插入到文字后方
    [scaleStr appendAttributedString:attributedImage];
   //如果要插入到前面
  // [scaleStr insertAttributedString:attributedImage atIndex:0];
    return scaleStr;
}

2.使用YYText庫,這個擴展性更好,如果做直播的話,可以用在聊天窗口,可以添加UIKit的控件,可以添加事件

- (YYTextLayout *)createTextImage:(NSString*)text witImage:(NSString*)imageName withSize:(CGSize)finalSize{
    UIFont *font = [UIFont systemFontOfSize:14];
    NSMutableAttributedString *textGold = [[NSMutableAttributedString alloc] initWithString:text attributes:@{NSForegroundColorAttributeName:[UIColor blackColor], NSFontAttributeName:font}];
  //可以添加UIKit的控件及事件
    UIImageView *imagImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
    NSMutableAttributedString *attachTextRecahrage = [NSMutableAttributedString yy_attachmentStringWithContent:imagImage contentMode:UIViewContentModeLeft attachmentSize:CGSizeMake(62, 22) alignToFont:font alignment:YYTextVerticalAlignmentCenter];
    [textGold  appendAttributedString:attachTextRecahrage];
    //如果要插入到前面
//    [textGold insertAttributedString:attachTextRecahrage atIndex:0];
    YYTextContainer *container = [YYTextContainer containerWithSize:CGSizeMake(finalSize.width, finalSize.height)]; //圖文混排需要的寬度及高度
    YYTextLayout *textLayout = [YYTextLayout layoutWithContainer:container text:textGold];
    return textLayout;
}
//使用
    YYLabel *labeShow = [[YYLabel alloc] initWithFrame:CGRectMake(0, 0,100, 50)];
    labeShow.textColor = [UIColor blackColor];
    labeShow.textLayout = [self createTextImage:@"文字" witImage:@"圖片" withSize:labeShow.size];
    labeShow.textAlignment = NSTextAlignmentLeft;
    [self.view addSubview:labeShow];
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容