【问题标题】:Split a string with '\n', insert it into UITableViewCell and get height用 '\n' 拆分字符串,将其插入 UITableViewCell 并获取高度
【发布时间】:2012-03-23 00:31:42
【问题描述】:

我正在使用最新的 SDK 和 XCode 4.2 开发一个 iOS 4 应用程序。

我使用网络服务来检索一些文本数据。我不知道它的长度,所以我需要拆分这些字符串以适应自定义 UITableViewCell

此自定义 UITableViewCell 将有一个 UILabel。这个标签会被从 web 服务中检索到的文本填充。

文本将是国家名称:西班牙、法国、美国、意大利等。我将处理这些名称以将它们附加到一个唯一字符串。我会这样做:“西班牙 - 法国 - 美国 - ...”.

我的一个问题是这条线可能很长,我需要将它分成几行以适应UILabel 的宽度。我已经解决了这个问题,每次添加' - '时检查字符串是否会大于 UILabel 宽度。所以,我会有这样的字符串:"Spain - France\nUSA - ..."。

好的。现在,我有一个带有 \n 的字符串,它可以放入 UILabel 中。所以,我需要修改UITableViewCell 高度以适应UILabel 高度。

但是,当我使用 [NSString sizeWithFont:[UIFont systemFontOfSize:kFontSize]]; 时,我并没有得到真正的高度,我总是得到 21.0f。

我发现这个tutorial 关于 UITableView 动态高度,但我不知道如何在我的代码中使用它。

简而言之,我需要将 ' - ' 字符附加到国家名称,但它有一个返回值(因为字符串将在另一行呈现通过 UILabel),我不必附加 ' - '。而且,当我得到这个字符串时,我必须将自定义 UITableViewCell 的大小调整为 UILabel 高度。

有什么线索吗?

【问题讨论】:

    标签: ios uitableview uilabel multiline


    【解决方案1】:

    这是你要找的东西吗?

    //create a CGFloat variable
    CGFloat _height = 0;
    //find out the size for your text. Instead of 255 insert the width of your label
    CGSize _textSize = [yourString sizeWithFont:[UIFont systemFontOfSize:kFontSize] constrainedToSize:(CGSize) { 255, 9999 }];
    //add the height of that CGSize variable to your height in case you will need to add more values
    _height += _textSize.height;
    //eventually some other calculations
    

    希望对你有帮助

    【讨论】:

    • 谢谢。我会试试看,我会告诉你的。
    • @VansFannel 这是我项目中的一段代码,几个月前它确实有效:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    • 1970-01-01
    • 2021-11-16
    • 1970-01-01
    • 1970-01-01
    • 2015-08-24
    • 1970-01-01
    相关资源
    最近更新 更多