如何调整属性字符串(Attributed String)中符号图片(Symbol Image)的大小
问题原因
符号图片无法调整大小的核心原因如下:
- 为UIImage配置的
UIImageSymbolConfiguration仅定义了符号图片自身的矢量参数,当图片作为NSTextAttachment被嵌入富文本由TextKit排版时,系统会默认将图片缩放适配当前富文本段落的默认字体尺寸(也就是你的文本使用的UIFontTextStyleBody字号),你设置的大尺寸配置被排版逻辑覆盖了 - 直接放到UIImageView中时没有富文本的排版约束,所以可以正常按配置的尺寸渲染
解决方法
你只需要显式指定NSTextAttachment的bounds属性即可控制符号图片的大小,同时可以调整Y轴偏移让符号和后面的文本基线对齐,避免出现高低错位。
修改后的完整代码
UILabel *label = [[UILabel alloc] init]; NSString *title = @"Some Text"; label.adjustsFontForContentSizeCategory = YES; // 定义文本使用的字体和符号使用的字体 UIFont *textFont = [UIFont preferredFontForTextStyle:UIFontTextStyleBody]; UIFont *symbolFont = [UIFont preferredFontForTextStyle:UIFontTextStyleLargeTitle]; NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@" %@", title] attributes:@{ NSFontAttributeName: textFont, NSForegroundColorAttributeName: [UIColor labelColor] }]; UIImageSymbolConfiguration *configuration = [UIImageSymbolConfiguration configurationWithFont:symbolFont]; UIImage *squareImage = [[UIImage systemImageNamed:@"square.fill" withConfiguration:configuration] imageWithTintColor:[UIColor systemBlueColor]]; NSTextAttachment *imageAttachment = [NSTextAttachment textAttachmentWithImage:squareImage]; // 核心修改:手动设置attachment的bounds,控制大小和对齐 CGFloat symbolSize = symbolFont.pointSize; // Y轴偏移调整让符号和文本基线对齐 CGFloat offsetY = (textFont.capHeight - symbolFont.capHeight) / 2; imageAttachment.bounds = CGRectMake(0, offsetY, symbolSize, symbolSize); [string insertAttributedString:[NSAttributedString attributedStringWithAttachment:imageAttachment] atIndex:0]; label.attributedText = string;
补充说明
如果你的App最低支持iOS 15及以上版本,也可以直接使用UIImageSymbolConfiguration作为富文本属性附加到附件对应的富文本片段上,不需要手动计算bounds:
NSAttributedString *attachmentString = [NSAttributedString attributedStringWithAttachment:imageAttachment]; [attachmentString addAttribute:NSImageSymbolConfigurationAttributeName value:configuration range:NSMakeRange(0, attachmentString.length)];
内容的提问来源于stack exchange,提问作者ashipma
相关产品推荐
相关产品推荐

