简体   繁体   中英

How to size a symbol image in an attributed string

I have a label where I am trying to put a symbol image at the start of the label and then some text after it. This works, but the symbol image never changes size. It doesn't matter what size I provide in the UIImageSymbolConfiguration, it stays small. If I take this code and put the image in a UIImageView, then the image gets larger as expected. Is there something wrong with anything I am doing here related to the symbol image configuration?

    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;

I stumbled upon the same issue as I was building a similar feature today. It seems that symbols work slightly differently when embedded in text attachments: it's the font set on the attributed string that determines the size, not the configuration of the symbol itself.

With this in mind, you simply need to make sure the range of the icon in the attributed string has a font set:

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

Note that you'll still need to configure the symbol if you intend to render using a different color. In this case, attributed strings will ignore the NSForegroundColorAttributeName attribute when rendering the symbol (resulting in a blank, zero-width symbol). I suspect this is because symbols have hierarchical colors, but I might be wrong.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM