简体   繁体   中英

iOS NSTextAttachment image not showing

NSTextAttachment lock image cut off at the edge but when the line does not breaks at the edge then the lock icon can be seen. I want the icon to move to the next line like a word move to the next line.

Here are the example:

    NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
    attachment.image = [UIImage imageNamed:@"lock.png"];
    NSString *stringHeadline = @"This is a example sample sentence. Why I do";
    NSAttributedString *attachmentLock = [NSAttributedString attributedStringWithAttachment:attachment];
    NSAttributedString *myText = [[NSMutableAttributedString alloc] initWithString:stringHeadline];
    NSMutableAttributedString *lockString = [[NSMutableAttributedString alloc] initWithAttributedString:myText];

    [lockString appendAttributedString:attachmentLock];
    lblHeadline.attributedText = lockString;
    [lblHeadline sizeToFit];

在此处输入图片说明

当文字靠近边缘时,“锁定”图标丢失。

Lock icon gone missing when the text near the edge.

Just append a space after your NSTextAttachment. Otherwise the NSTextAttachment does not change to a new line like a normal text does when there's not enough space for it. I believe this's a bug of Apple.

Your code should likes like this:

NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
attachment.image = [UIImage imageNamed:@"lock.png"];
NSString *stringHeadline = @"This is a example sample sentence. Why I do";
NSAttributedString *attachmentLock = [NSAttributedString attributedStringWithAttachment:attachment];
NSAttributedString *myText = [[NSMutableAttributedString alloc] initWithString:stringHeadline];
NSMutableAttributedString *lockString = [[NSMutableAttributedString alloc] initWithAttributedString:myText];

[lockString appendAttributedString:attachmentLock];
/** 
 * Here I'm adding a space after NSTextAttachment just to make sure that
 * the NSTextAttachment will auto change to next line like normal text does.
 * Otherwise the NSTextAttachment does not move to the new line.
 */
[lockString appendAttributedString: [[NSAttributedString alloc] initWithString:@" "]];
lblHeadline.attributedText = lockString;
[lblHeadline sizeToFit];

Check out more about my solution by checking my Post Attach Stars to the End of a UILabel .

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