ios - 如何调整属性字符串中符号图像的大小

标签 ios uilabel nsattributedstring nstextattachment sf-symbols

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

相关文章:

ios - 应用程序转换为 ARC,现在收到有关我的属性的警告

objective-c - UILabel字体大小?

ios - 在 NSAttributedString 的 drawWithRect 中查找最后可见的行索引

ios - Swift - 无法从文件读取/写入

ios - 不知道为什么当我点击单元格表时弹出 "label"

iOS - 使 UIImageView 调整大小以适应 UILabel 和 AutoLayout

ios - 是否允许在 UILabel 的下拉列表中列出自定义字体?

iOS - IB 中的 UILabel attributedText 无法更改字体大小

ios - NSUnderlineStyle 属性名称 下划线间距

ios - 访问另一个类中的属性