Nil*_*nch 17 objective-c uitableview nsstring uilabel emoji
在UITableView
需要显示一长串聊天对话(通常包含表情符号)的情况下,会发生大小计算错误.
我的问题是,如果一个字符串是正确的长度,我使用sizeWithFont
,我在我的第一次测量使用sizewithfont
得到一个不正确的字符串长度,导致"换行".
我认为这是因为字符串":-)"比实际的笑脸图标更宽.
证据可以在这里看到:
但他们建议改用sizeToFit,所以我决定试一试.
巴姆,同样的结果.
有谁知道怎么反击这个?有没有boolean
检查"标签是否被表情符号处理",所以我可以跳过该电话?
两次运行相同的行什么也没做,看起来需要绘制视图,然后才sizeWithFont
意识到它的错误.
显示的列在- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
自定义单元格中的段中运行.我也可以在一个完美的常规UITableViewCell上复制错误,所以这似乎不是它.
小智 13
- (CGFloat)heightStringWithEmojis:(NSString*)str fontType:(UIFont *)uiFont ForWidth:(CGFloat)width {
// Get text
CFMutableAttributedStringRef attrString = CFAttributedStringCreateMutable(kCFAllocatorDefault, 0);
CFAttributedStringReplaceString (attrString, CFRangeMake(0, 0), (CFStringRef) str );
CFIndex stringLength = CFStringGetLength((CFStringRef) attrString);
// Change font
CTFontRef ctFont = CTFontCreateWithName((__bridge CFStringRef) uiFont.fontName, uiFont.pointSize, NULL);
CFAttributedStringSetAttribute(attrString, CFRangeMake(0, stringLength), kCTFontAttributeName, ctFont);
// Calc the size
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(attrString);
CFRange fitRange;
CGSize frameSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRangeMake(0, 0), NULL, CGSizeMake(width, CGFLOAT_MAX), &fitRange);
CFRelease(ctFont);
CFRelease(framesetter);
CFRelease(attrString);
return frameSize.height + 10;
}
Run Code Online (Sandbox Code Playgroud)
谢谢@SergiSolanellas!这是一个带有referencedString的版本,缩短了方法,因为文本和字体已经设置好了.
//
// Given an attributed string that may have emoji characters and the width of
// the display area, return the required display height.
//
- (CGFloat)heightForAttributedStringWithEmojis:(NSAttributedString *)attributedString forWidth:(CGFloat)width {
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attributedString);
CFRange fitRange;
CGSize frameSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRangeMake(0, 0), NULL, CGSizeMake(width, CGFLOAT_MAX), &fitRange);
CFRelease(framesetter);
return frameSize.height;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3532 次 |
最近记录: |