Button / Label 横向图文混排
随笔而已 ,自己做个记录
此方法封装样式是(文字 图片 文字) 返回attributedString 类型,所以button 和 Label 通用,图片固定被写死,可加传参
-(NSMutableAttributedString*)getBtnAttributedString:(NSString*)attriStr lastAttri:(NSString*)attLast
{ ///创建第一段富文本 NSMutableAttributedString*attri =[[NSMutableAttributedString alloc]initWithString:attriStr]; /// 创建最后一段富文本 NSMutableAttributedString*attriLast = [[NSMutableAttributedString alloc]initWithString:attLast];
///创建中间图片富文本 NSTextAttachment*attch = [[NSTextAttachment alloc]init]; attch.image= [UIImage imageNamed:@"ic_sx"]; ///图片占位大小 也可用image.size属性 自动计算 attch.bounds=CGRectMake(0,5,37/2,11/2); NSAttributedString*string = [NSAttributedStringattributedStringWithAttachment:attch];
/// 加入图片 [attri appendAttributedString:string];
///加入最后一段文字 [attri appendAttributedString:attriLast];
[attri addAttribute:NSForegroundColor AttributeNamevalue:UIColorFromRGB(0x4083F5) range:NSMakeRange(0,3)];
[attri addAttribute:NSForegroundColor AttributeNamevalue:UIColorFromRGB(0x4083F5) range:NSMakeRange(attri.length-1,1)];
[attri addAttribute:NSFontAttributeNamevalue:Font_Title16 range:NSMakeRange(0,3)];
[attri addAttribute:NSFontAttributeNamevalue:Font_Title16 range:NSMakeRange(attri.length-1,1)];
return attri ;
}
[btn setAttributedTitle:[self getBtnAttributedString:strAttri lastAttri:strAttriLast] forState:UIControlStateNormal];
还有一种是要计算文字和图片的宽高,修改btn.imageEdgeInsets 和 btn.imageEdgeInsets 的值来排版文字和图片,网上很多,不做赘述,想写再写。
最后祝自己越来越帅,白富美向我表白
网友评论