// 设置label每一行文字的最大宽度 // 为了保证计算出来的数值 跟 真正显示出来的效果 一致 self.contentLabel.preferredMaxLayoutWidth = [UIScreen mainScreen].bounds.size.width - 20;
下面通过例子,给UILabel的文字后面跟上一个表情:
//创建NSTextAttachment NSTextAttachment *attachment = [[NSTextAttachment alloc] init]; attachment.image = [UIImage imageNamed:@"emoji"]; NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"后面跟着图片"]; [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 6)]; [attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:16] range:NSMakeRange(0, 6)]; NSAttributedString *attachmentString = [NSAttributedString attributedStringWithAttachment:attachment]; [attributedString insertAttributedString:attachmentString atIndex:6]; //设置attributedText _label.attributedText = attributedString;
效果如下:
上图的例子中,emoji图片偏大,位置也偏上,如何调整?参考Center NSTextAttachment image next to single line UILabel。
可以通过调整bounds
来解决:
NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
attachment.image = [UIImage imageNamed:@"emoji"];
attachment.bounds = CGRectMake(0, -5, 20, 20);
调整之后的效果如下:
也可以继承NSTextAttachment
,然后重写- (CGRect)attachmentBoundsForTextContainer:(NSTextContainer *)textContainer proposedLineFragment:(CGRect)lineFrag glyphPosition:(CGPoint)position characterIndex:(NSUInteger)charIndex
方法:
@interface MYNSAttachment : NSTextAttachment @end @implementation MYNSAttachment - (CGRect)attachmentBoundsForTextContainer:(NSTextContainer *)textContainer proposedLineFragment:(CGRect)lineFrag glyphPosition:(CGPoint)position characterIndex:(NSUInteger)charIndex { return CGRectMake( 0 , -5 , lineFrag.size.height , lineFrag.size.height); }
@end
UIFont
UIFont代表字体,常见创建方法有以下几个:
+ (UIFont *)systemFontOfSize:(CGFloat)fontSize; 系统默认字体
+ (UIFont *)boldSystemFontOfSize:(CGFloat)fontSize; 粗体
+ (UIFont *)italicSystemFontOfSize:(CGFloat)fontSize; 斜体