【问题标题】:sizewithfont always returns the same value no matter what string is used无论使用什么字符串,sizewithfont 总是返回相同的值
【发布时间】:2012-11-09 08:53:29
【问题描述】:

我想根据它的文本计算一个 tableviewcell 的高度。我正在使用

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

但不知何故,返回值总是 22(字体大小)。奇怪的是,当我使用时

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

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

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

【问题讨论】:

    标签: ios uitableview sizewithfont


    【解决方案1】:

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

    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 Additions Reference

    编辑:

    我刚试过这段代码:

    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}
    

    CGSizestruct

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

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

    EDIT2:

    来自文档sizeWithFont:forWidth:lineBreakMode:

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

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

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

    请参阅this answer

    【讨论】:

    • 很抱歉造成混淆,但 userLabel 实际上是 NSString 类型。所以有人知道为什么第一个不起作用而第二个起作用?
    • 你能检查(用NSLog[tableView frame].size的大小吗?
    • 或者尝试(只是为了检查)[userLabel sizeWithFont:[UIFont fontWithName:@"Arial" size:18.0f] 返回的内容。
    • [tableView frame].size 是 320,[userLabel sizeWithFont:[UIFont fontWithName:@"Arial" size:18.0f] 是 22
    • 很抱歉 - 现在很清楚 :)。是的,如果字符串太宽(一行),该方法只会截断字符串。这就是为什么你应该使用第二个选项。
    【解决方案2】:

    我认为这样更容易。设置好userLabel的“text”属性后,调用该方法。

    [userLabel sizeToFit];
    

    此时,userLabel.frame 已更改,使其适合所选字体的文本。您可以使用 userLabel.frame.size.height 来调整您的表格视图单元格。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-20
      • 1970-01-01
      • 2019-06-26
      • 1970-01-01
      • 2014-05-18
      • 2018-09-24
      相关资源
      最近更新 更多