Reputation: 3203
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.
Upvotes: 4
Views: 6511
Reputation: 8461
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.
Upvotes: 8