4

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];

enter image description here

Lock icon gone missing when the text near the edge.

Lock icon gone missing when the text near the edge.

4

1 に答える 1

6

NSTextAttachment の後にスペースを追加するだけです。そうしないと、十分なスペースがない場合に通常のテキストが行うように、NSTextAttachment が新しい行に変更されません。これはAppleのバグだと思います。

コードは次のようになります。

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];

私の Post Attach Stars to the End of a UILabel をチェックして、私のソリューションの詳細を確認してください。

于 2015-02-04T10:53:01.727 に答える