iOS 文本处理 ----- 两行文本后面添加 ... 查看更多

来源:互联网 发布:java游戏编程书 编辑:程序博客网 时间:2024/06/05 19:08
* 业务需求是是这样的,需要我们在一段文本后面添加 展开 展开后文本是多少就显示多少。
顶顶顶顶顶顶顶顶顶顶的大多数是是是是谁谁谁水水水水是是是是是...查看更多
顶顶顶顶顶顶顶顶顶顶的大多数是是是是顶顶顶顶顶顶顶顶顶顶顶顶顶顶顶顶顶顶谁谁谁水水水水是是是是是是是是是是撒大多数是山东省撒打算打算打算打算的收水电费第三方第三方说的发送到发送到范水电费第三方士大夫士大夫。

实现思路:

1.计算两行文本可以显示文本的个数

2.截取字符串

3.拼接字符( ... 和 查看更多)两个都拼接上去

4.给查看更多文本(富文本)添加事件


问题:主要问题在于 思路1

如何知道两行文本可以显示多少个字数,而且文本可能有标点,数字、英文、中文  它们的宽度是不一致的。 

意思就是:两行文本可以显示的个数 是根据具体需要显示文本内容来决定的。


上代码  使用到 coreText 框架 

CTFramesetterCreateFrame(framesetter,CFRangeMake(0,0), bezierPath.CGPath,NULL);


/**

 返回两行文本的range

 */

- (NSRange)getTwoTextRangeWith:(NSString *)string {

    NSMutableDictionary * attributes = [NSMutableDictionary dictionaryWithCapacity:5];

    UIFont * font = [UIFont systemFontOfSize:14.0];

    [attributes setValue:font forKey:NSFontAttributeName];

    NSAttributedString * attributedString = [[NSAttributedString alloc] initWithString:string/*需要分页的字符串*/ attributes:attributes];

    CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef) attributedString);

    UIBezierPath * bezierPath = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0, App_Frame_Width - 16, 42)];

    CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), bezierPath.CGPath, NULL);

    CFRange range = CTFrameGetVisibleStringRange(frame);

    CFRelease(frame);

    CFRelease(framesetter);

   

    NSRange rg = NSMakeRange(range.location, range.length);

    return rg;

}




后面的工作就自己截取字符串了。




1 0
原创粉丝点击