开发者

IOS equivalent to Android's Paint.breakText()

开发者 https://www.devze.com 2023-02-20 08:11 出处:网络
I\'m looking for the iOS objective c equivalent to Android\'s Paint.breakText(). I have a string that is being put in a rectangle. If it doesn\'t fit, I need to find the index of the character to rep

I'm looking for the iOS objective c equivalent to Android's Paint.breakText().

I have a string that is being put in a rectangle. If it doesn't fit, I need to find the index of the character to replace with an ellipsis and drop the rest of the string.

Edit:

As James Bedford's answer hints at, this problem can be solved with the UIKit NSString additions.

[foo drawInRect:someRect withFont:someFont
     lineBreakMode:UILineBreakModeTailTruncation];

UILineBreakModeTailTruncation, when used in conjuncti开发者_运维知识库on with drawing, will add an ellipsis to the end of the string.


I know this isn't what you asked for, but the easiest way would be to use a UILabel, set it to be multiLine and then it'll truncate and ellipsize for you.

Now having said this, you can use CoreText to do what you want. CTFrameSetter and TypeSetters can provide line breaking information, with indexes.

I'd provide an example, but I haven't used these classes yet.


Have you tried using the sizeWithFont: methods in the NSString UIKit Additions category, referenced here?

Edit:

The best I can up with is to write an algorithm that tries each length of the string you want using these sizeWithFont: methods until the string can no longer be fitted into the box. At this point, you know you need to go three characters back to allow room for your ellipsis. You should be able to optimize this algorithm to O(log(n)).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号