NSTextAttachment锁定图像在边缘处被切断,但当线在边缘处未中断时,则可以看到锁定图标。我希望图标移动到下一行,就像一个单词移动到下一行。
示例如下:
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];


当文本靠近边缘时,锁形图标消失。
发布于 2015-02-04 18:53:02
只需在NSTextAttachment后面追加一个空格即可。否则,当空间不足时,NSTextAttachment不会像普通文本那样更改为新行。我相信这是苹果的一个bug。
您的代码应该如下所示:
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];查看我的帖子Attach Stars to the End of a UILabel,了解有关我的解决方案的更多信息。
https://stackoverflow.com/questions/25301404
复制相似问题