无论使用什么字符串,sizewithfont 总是返回相同的值 [英] sizewithfont always returns the same value no matter what string is used

查看:26
本文介绍了无论使用什么字符串,sizewithfont 总是返回相同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据文本计算tableviewcell的高度.我正在使用

I want to calculate the height of a tableviewcell according to its text. I'm using

CGSize userInputSize = [userLabel sizeWithFont:[UIFont fontWithName:@"Arial" size:18.0f] forWidth:[tableView frame].size.width-10 lineBreakMode:NSLineBreakByWordWrapping]  

但不知何故,返回值始终为 22(字体大小).奇怪的是,当我使用

but somehow the return value is always 22 (size of the font). Strange thing is that when I'm using

CGSize userInputSize = [userLabel sizeWithFont:[UIFont fontWithName:@"Arial" size:18.0f] constrainedToSize:[tableView frame].size lineBreakMode:NSLineBreakByWordWrapping];

一切正常.但我更喜欢第一个版本,这样我就可以轻松调整宽度.为什么它不起作用?

all works fine. But I would prefer the first version, so I can easily adjust the width. Why isn't it working?

抱歉命名约定不好,但 userLabel 是 NSString 而不是标签

sorry for the bad name convention, but userLabel is a NSString not a label

推荐答案

sizeWithFont 是一个 NSString 方法(UIKit 添加).使用:

sizeWithFont is a NSString method (UIKit additions). use:

CGSize userInputSize = [userLabel.text sizeWithFont:[UIFont fontWithName:@"Arial" size:18.0f] constrainedToSize:[tableView frame].size lineBreakMode:NSLineBreakByWordWrapping];

CGSize userInputSize = [userLabel.text sizeWithFont:userLabel.font constrainedToSize:[tableView frame].size lineBreakMode:NSLineBreakByWordWrapping];

参见 NSString UIKit 添加参考.

我刚试过这个代码:

NSLog (@"test: %@", NSStringFromCGSize([@"test" sizeWithFont:[UIFont fontWithName:@"Arial" size:18.0f]]));
NSLog (@"longer test: %@", NSStringFromCGSize([@"longer test" sizeWithFont:[UIFont fontWithName:@"Arial" size:18.0f]]));

结果是:

test: {30, 22}
longer test: {85, 22}

CGSize 是一个 struct:

struct CGSize {
   CGFloat width;
   CGFloat height;
};
typedef struct CGSize CGSize;

所以您可能正在查看 size.height 而不是 size.width

So you're probably looking at size.height instead of size.width

来自文档 sizeWithFont:forWidth:lineBreakMode:

如果字符串的大小超过了给定的宽度,这个方法使用指定的行截断文本(仅用于布局目的)中断模式,直到它符合最大宽度;然后它返回生成的截断字符串的大小.

If the size of the string exceeds the given width, this method truncates the text (for layout purposes only) using the specified line break mode until it does conform to the maximum width; it then returns the size of the resulting truncated string.

所以你最好定义一个最大尺寸(真正的 width 和一个大的 height)并使用:

So you'll be better of defining a maximum size (real width and a big height) and go with the:

- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(UILineBreakMode)lineBreakMode

请参阅此答案.

这篇关于无论使用什么字符串,sizewithfont 总是返回相同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆