我有一个标签,我试图在标签的开头放置一个符号图像,然后在其后面放置一些文本。这是可行的,但符号图像永远不会改变大小。我在 UIImageSymbolConfiguration 中提供什么大小并不重要,它仍然很小。如果我使用此代码并将图像放入 UIImageView 中,则图像会按预期变大。我在这里所做的与符号图像配置相关的事情是否有问题?
UILabel *label = [[UILabel alloc] init];
NSString *title = @"Some Text";
label.adjustsFontForContentSizeCategory = YES;
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@" %@", title] attributes:@{
NSFontAttributeName: [UIFont preferredFontForTextStyle:UIFontTextStyleBody],
NSForegroundColorAttributeName: [UIColor labelColor]
}];
UIImageSymbolConfiguration *configuration = [UIImageSymbolConfiguration configurationWithFont:[UIFont preferredFontForTextStyle:UIFontTextStyleLargeTitle]];
UIImage *squareImage = [[UIImage systemImageNamed:@"square.fill" withConfiguration:configuration] imageWithTintColor:[UIColor systemBlueColor]];
NSTextAttachment *imageAttachment = [NSTextAttachment textAttachmentWithImage:squareImage];
[string insertAttributedString:[NSAttributedString attributedStringWithAttachment:imageAttachment] atIndex:0];
label.attributedText = string;
最佳答案
我今天在构建类似功能时偶然发现了同样的问题。当嵌入文本附件时,符号的工作方式似乎略有不同:确定大小的是属性字符串上设置的字体,而不是符号本身的配置。
考虑到这一点,您只需确保属性字符串中的图标范围具有字体集:
UIFont *font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];
[string addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, 1)];
请注意,如果您打算使用不同的颜色进行渲染,您仍然需要配置符号。在这种情况下,属性字符串在渲染符号时将忽略 NSForegroundColorAttributeName
属性(导致空白、零宽度符号)。我怀疑这是因为符号具有分层颜色,但我可能是错的。
关于ios - 如何调整属性字符串中符号图像的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70194327/