在需要显示一长串类似聊天的对话(通常包含表情符号)的UITableView中,会出现大小计算错误。
我的问题是,如果一个字符串的长度恰到好处,并且我使用了sizeWithFont,那么在我第一次使用sizewithfont进行测量时,我得到的字符串长度是不正确的,这会导致“换行”。
我假设这是因为字符串":-)“比实际的笑脸图标更宽。
证据可以在这里看到:

现在,在其他一些堆栈中,一些人声称sizeWithFont将只考虑字符串,而不是表情符号,这对我来说没有意义,因为它“最终”是正确的……
但是他们建议使用sizeToFit,所以我决定试一试。

Bam,结果一样。
有人知道如何应对这种情况吗?有没有boolean可以检查“标签是否已完成表情处理”,这样我就可以跳过那次通话了?
运行同一条线两次没有任何作用,似乎需要绘制视图,然后sizeWithFont才会意识到它的错误。
所显示的列在自定义单元格上的- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath段中运行。我也可以在一个完全正常的UITableViewCell上复制这个错误,所以似乎不是这样。
发布于 2014-03-21 19:15:26
- (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;
}发布于 2014-07-23 13:56:06
感谢@SergiSolanellas!下面是一个采用attributedString的版本,缩短了方法,因为文本和字体已经设置好了。
//
// 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;
}发布于 2018-09-03 12:41:05
我正在使用UILabel
大小(_sizeThatFits: CGSize) -> CGSize
这对我很管用。
我的代码
let tempLabel = UILabel()
tempLabel.font = font
tempLabel.attributedText = attText
tempLabel.numberOfLines = 0
let size = tempLabel.sizeThatFits(CGSize(width: 200, height:CGFloat.greatestFiniteMagnitude))作为代码,您需要分配三个属性。
https://stackoverflow.com/questions/19537354
复制相似问题