在我的应用程序中,如果文本输入很大,我需要将“阅读更多”设置到文本视图中。所以我的方法是找到适合文本视图的字符串范围,并将“查看更多”附加到它。有什么方法可以实现它在 Swift 中。要求是模拟阅读更多选项,以在点击时像 facebook 一样在详细视图中显示完整的文本。
您正在寻找的功能是CTFramesetterSuggestFrameSizeWithConstraints。本质上,它可以让您找出适合特定框架的字符数。您可以使用该数字来截断当前文本并插入按钮。
我为 UILabel 的子类编写了此函数的实现:
- (NSInteger)numberOfCharactersThatFitLabel {
// Create an 'CTFramesetterRef' from an attributed string
CTFontRef fontRef = CTFontCreateWithName((CFStringRef)self.font.fontName, self.font.pointSize, NULL);
NSDictionary *attributes = [NSDictionary dictionaryWithObject:(__bridge id)fontRef forKey:(id)kCTFontAttributeName];
CFRelease(fontRef);
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:self.text attributes:attributes];
CTFramesetterRef frameSetterRef = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attributedString);
// Get a suggested character count that would fit the attributed string
CFRange characterFitRange;
CTFramesetterSuggestFrameSizeWithConstraints(frameSetterRef, CFRangeMake(0,0), NULL, CGSizeMake(self.bounds.size.width, self.numberOfLines*self.font.lineHeight), &characterFitRange);
CFRelease(frameSetterRef);
return (NSInteger)characterFitRange.length;
}
这是一篇博文用于完全实现将随机文本剪切到指定的行数并向其附加“查看更多”文本。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)