我有一个带有图像的属性字符串 (NSTextAttachment
)。这工作正常,但我遇到了一个我似乎无法解决的截断问题。
在示例中,假设字符串 ##
是图像。所以我的字符串看起来像 Hello world! ##
。尾部截断设置在段落样式上。
现在,如果空间受限,文本将被省略号截断(这是我想要的)。但不幸的是,图像也被截断了。
所以结果是这样的:
Hello w...
但我希望它看起来像:
Hello...##
也就是说,我希望图片附件不会被截断,它应该始终可见。
附件的原因是我希望图像总是在字符串的末尾,所以当文本很短时图像在末尾,当文本换行到多行时我也希望图像在最后。尝试手动将图像定位在“外部”是行不通的,因为文本不会被正确截断。
那么,有没有办法告诉 NSAttributedString
不要截断图像?
生成属性字符串的示例代码:
NSString *title;
NSMutableAttributedString *attributedString;
NSMutableParagraphStyle *paragraph;
NSDictionary *attributes;
NSTextAttachment *attachment;
paragraph = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
paragraph.hyphenationFactor = 1.0;
paragraph.lineBreakMode = NSLineBreakByTruncatingTail;
attributes = @{
NSForegroundColorAttributeName : [self titleTextColor],
NSParagraphStyleAttributeName : paragraph,
};
title = @"Hello world!";
attributedString = [[NSMutableAttributedString alloc] initWithString:title
attributes:attributes];
attachment = [[NSTextAttachment alloc] init];
attachment.image = [UIImage imageNamed:@"myImage"];
[attributedString appendAttributedString:[NSAttributedString attributedStringWithAttachment:attachment]];
[attachment release];
self.titleLabel.attributedText = attributedString;
[attributedString release];
[paragraph release];
编辑:其中一个重要部分(在上面的描述中略有遗漏)是该解决方案需要适用于多行文本。
最佳答案
我认为您无法通过“技巧”获得预期的结果。你必须做真正的工作:子类 NSTextContainer
并覆盖 -lineFragmentRectForProposedRect:atIndex:writingDirection:remainingRect:
.这包括设置您自己的文本堆栈。
代码太长就不贴在这里了。但是文档中有一些示例。 (OS X的文档更丰富,IIRC。有差异,但你可以用它来基本了解部分。)所以这个答案仍然是一个指针。
由于您住在慕尼黑,我假设您懂德语。因此,我想提一下,在我的书的第二部分(第 6 章)中有一个代码示例,用于围绕中间孔布置文本的 View 。您可以通过在末尾保留一个矩形来执行相同的操作。
希望对您有所帮助!
关于objective-c - 带有文本附件和截断的属性字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22782146/