1

我有一个标签,我试图在标签的开头放置一个符号图像,然后在其后放置一些文本。这有效,但符号图像永远不会改变大小。我在 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;
4

1 回答 1

1

我偶然发现了同样的问题,因为我今天正在构建一个类似的功能。嵌入文本附件时,符号的工作方式似乎略有不同:决定大小的是属性字符串上设置的字体,而不是符号本身的配置。

考虑到这一点,您只需确保属性字符串中图标的范围具有字体集:

UIFont *font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];
[string addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, 1)];

请注意,如果您打算使用不同的颜色进行渲染,您仍然需要配置符号。在这种情况下,属性字符串将在渲染符号时忽略该NSForegroundColorAttributeName属性(导致空白、零宽度符号)。我怀疑这是因为符号具有分层颜色,但我可能错了。

于 2022-01-28T18:06:23.850 回答