drawInRect などでStringを描画する場合(UILabelなどでもそうだが)、Paragraphが対象の場合は、指定範囲で途中で切れたStringに自動的に...をつけてくれるTail Truncationにするには、下記のようにlineBreakModeにByTruncatingTailを指定したAttributeを作ればいい。
let style = NSMutableParagraphStyle()
style.lineBreakMode =.ByTruncatingTail
style.alignment = NSTextAlignment.Left
let stringAttrubute = [
NSParagraphStyleAttributeName: style
]
しかし、Paragraph は Word Wrapping して同時に描画範囲内で Tail Truncation したい場合どうすればいいのだろう。
例えば、下の図のような感じにしたい。図の文章のあとにまだ文章は続いているが、draw範囲はそれより小さいのだ。
ちなみに以下のような指定はエラーになる。
style.lineBreakMode = .ByTruncatingTail | .ByWordWrapping
↓結論
drawWithRect のoptionsの指定に TruncatesLastVisibleLine があるからこれを使えばいいと分かったのでのメモ。
NSMutableParagraphStyle は ByWordWrapping にして、drawWithRect でTruncatesLastVisibleLine 指定。
let style = NSMutableParagraphStyle()
style.lineBreakMode =.ByWordWrapping
style.alignment = NSTextAlignment.Left
let stringAttrubute = [
NSParagraphStyleAttributeName: style
]
let sampleText = "このStringは、このように...(略)...するようにしたい。途中で改行がはいるのである。\nどうすればいいのだろう?あ、できた!\nそして、まだまだStringは続く....(略)...."
sampleText.drawWithRect(
CGRectMake(0,0,800,300),
options: .UsesLineFragmentOrigin | .TruncatesLastVisibleLine,
attributes: stringAttrubute as [NSObject : AnyObject],
context: nil)
ちなみに、Objective-Cでは下記だけでこれができていた(ような気がする)。
[sampleText drawInRect:CGRectMake(0,0,800,300)
withFont: font
lineBreakMode:NSLineBreakByTruncatingTail];