问题
What I need
I need to write some text to a PDF. The text itself can be any length, but I can only display 2 lines (by word wrapping) and should truncate the tail in the second line if the space isn't enough.
What I've tried
NSMutableParagraphStyle *text = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];
text.lineBreakMode = NSLineBreakByTruncatingTail;
This way, the text goes only in the first line, and truncates at the end of the line.
NSMutableParagraphStyle *text = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];
text.lineBreakMode = NSLineBreakByWordWrapping;
This way, the text wraps to the second line, but if there's enough text for more lines, there's no truncating at the end of the second line.
I need some way to combine these two behaviours.
What I've researched
I've found some questions about problems with word wrapping, but nothing like this. The nearest I've got was this:
NSLineBreakByWordWrapping on First Line but NSLineBreakByTruncatingTail For Second Line?
But the problem there was different. In that question, the asker wants this behaviour but in a label, and he fixes the problem with some storyboard configuration that I've also used in other part of my project. But this question is about this behaviour in a PDF, using the NSStringDrawingContext
drawInRect
method.
I'm using iOS 7 (actually just updated to 7.1, but the situation is the same in both).
Thanks in advance.
Edit - also, I've looked this link before asking, but with no help:
https://developer.apple.com/library/ios/documentation/cocoa/reference/ApplicationKit/Classes/NSParagraphStyle_Class/Reference/Reference.html#//apple_ref/doc/c_ref/NSLineBreakByWordWrapping
回答1:
Refer to :
@interface NSAttributedString (NSExtendedStringDrawing)
- (void)drawWithRect:(CGRect)rect options:(NSStringDrawingOptions)options context:(NSStringDrawingContext *)context NS_AVAILABLE_IOS(6_0);
- (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options context:(NSStringDrawingContext *)context NS_AVAILABLE_IOS(6_0);
@end
Pass "NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingTruncatesLastVisibleLine" for options, please note this method is only available for NSAttributedString.
回答2:
Answer in Swift 4,
let str = NSMutableAttributedString(string: "long string")
str.draw(with: label.frame, options: [NSStringDrawingOptions.usesLineFragmentOrigin, .truncatesLastVisibleLine], context: nil)
label.numberOfLines = 0
label.attributedText = str.copy() as? NSAttributedString
来源:https://stackoverflow.com/questions/22396347/ios-combine-nslinebreakbywordwrapping-and-nslinebreakbytruncatingtail