根据UILabel动态调整uitableViewCell的大小(带段落间距)

2024-04-21

我有一个 UITableView,它由 JSON 文件中的文本和图像填充。 TableView 单元格当前对于文本中不包含许多换行符的“帖子”大小正确,但是我无法让它计算具有 4 或 5 个换行符的“帖子”的正确高度。

获取高度的代码:

-(float)height :(NSMutableAttributedString*)string
{
  NSString *stringToSize = [NSString stringWithFormat:@"%@", string];

  CGSize constraint = CGSizeMake(LABEL_WIDTH - (LABEL_MARGIN *2), 2000.f);

  CGSize size = [stringToSize sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:contraint lineBreakMode:NSLineBreakByWordWrapping];

  return size.height;
}

如何在允许换行和空白的情况下计算正确的大小?

EDIT

该方法的其余部分,

TableView CellForRow 内部:

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *row = [NSString stringWithFormat:@"%i", indexPath.row];

float postTextHeight = [self height:postText];

NSString *height = [NSString stringWithFormat:@"%f", heightOfPostText + 70];

[_cellSizes setObject:height forKey:row];
}

以及表格单元格的高度:

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *imageHeightString = [NSString stringWithFormat:@"%@", [_cellSizes objectForKey:indexPath.row]];

float heightOfCell = [imageHeightString floatValue];

 if (heightOfCell == 0) {
    
    return 217;
};

return heightOfCell + 5;
}

最好先计算高度,不要在方法中包含高度计算部分:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

最好用方法来计算:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 

因为你从 json 获取数据,所以你很容易计算 在“heightForRowAtIndexPath”方法中。

以下代码将给出计算文本高度的示例,根据您的要求更改它。 希望这对你有帮助:)

// i am using an array 
- (void)viewDidLoad
{
   [super viewDidLoad]; 
   // Do any additional setup after loading the view, typically from a nib.

   UIFont *labelFont = [UIFont fontWithName:@"Noteworthy-Bold" size:20];
   NSDictionary *arialdict = [NSDictionary dictionaryWithObject:labelFont forKey:NSFontAttributeName];

   NSMutableAttributedString *message = [[NSMutableAttributedString alloc] initWithString:@"this is just the sample example of how to calculate the dynamic height for tableview cell which is of around 7 to 8 lines. you will need to set the height of this string first, not seems to be calculated in cellForRowAtIndexPath method." attributes:arialdict];

   array = [NSMutableArray arrayWithObjects:message, nil];
   NSMutableAttributedString *message_1 = [[NSMutableAttributedString alloc] initWithString:@"you will need to set the height of this string first, not seems to be calculated in cellForRowAtIndexPath method." attributes:arialdict];
  [array addObject:message_1];   
}

 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
 {
     return 2;
 }

 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
 {
     return 2;
 }


 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   UITableViewCell *Cell = [self.aTableView dequeueReusableCellWithIdentifier:@"cell"];
   if(Cell == nil)
    {
       Cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
     }

     //dont include the height calculation part hear, becz heights are already set for all the cell 
    [Cell.textLabel sizeToFit];
    Cell.textLabel.attributedText = [array objectAtIndex:indexPath.row]; // dont calculate height hear it will be called after "heightForRowAtIndexPath" method
    Cell.textLabel.numberOfLines = 8;
    return Cell;
 }

  // put ur height calculation method i took some hardcoded values change it :)
  -(float)height :(NSMutableAttributedString*)string
 {
    /*
      NSString *stringToSize = [NSString stringWithFormat:@"%@", string]; 
  // CGSize constraint = CGSizeMake(LABEL_WIDTH - (LABEL_MARGIN *2), 2000.f);
     CGSize maxSize = CGSizeMake(280, MAXFLOAT);//set max height //set the constant width, hear MAXFLOAT gives the maximum height

     CGSize size = [stringToSize sizeWithFont:[UIFont systemFontOfSize:20.0f] constrainedToSize:maxSize lineBreakMode:NSLineBreakByWordWrapping];
return size.height; //finally u get the correct height
    */
     //commenting the above code because "sizeWithFont: constrainedToSize:maxSize: lineBreakMode: " has been deprecated to avoid above code use below

    NSAttributedString *attributedText = string;
    CGRect rect = [attributedText boundingRectWithSize:(CGSize){225, MAXFLOAT}
                           options:NSStringDrawingUsesLineFragmentOrigin
                              context:nil];//you need to specify the some width, height will be calculated
    CGSize requiredSize = rect.size;
    return requiredSize.height; //finally u return your height
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
 {
     //whatever the height u need to calculate calculate hear only    
     CGFloat heightOfcell = [self height:[array objectAtIndex:indexPath.row]];
     NSLog(@"%f",heightOfcell);
     return heightOfcell;
 }

希望这对你有帮助:)

For SWIFT version

class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate 
{

var messageArray:[String] = [] //array to holde the response form son for example 
override func viewDidLoad()
{
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    messageArray = ["One of the most interesting features of Newsstand is that once an asset downloading has started it will continue even if the application is suspended (that is: not running but still in memory) or it is terminated. Of course during while your app is suspended it will not receive any status update but it will be woken up in the background",
                    "In case that app has been terminated while downloading was in progress, the situation is different. Infact in the event of a finished downloading the app can not be simply woken up and the connection delegate finish download method called, as when an app is terminated its App delegate object doesn’t exist anymore. In such case the system will relaunch the app in the background.", 
                    " If defined, this key will contain the array of all asset identifiers that caused the launch. From my tests it doesn’t seem this check is really required if you reconnect the pending downloading as explained in the next paragraph.",
                    ]
}

func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
    return 1;
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
    return messageArray.count;
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
    var cell:UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("CELL") as? UITableViewCell;
    if(cell == nil)
    {
        cell = UITableViewCell(style:UITableViewCellStyle.Default, reuseIdentifier: "CELL")
        cell?.selectionStyle = UITableViewCellSelectionStyle.None
    }
    cell?.textLabel.font = UIFont.systemFontOfSize(15.0)
    cell?.textLabel.sizeToFit()
    cell?.textLabel.text = messageArray[indexPath.row]
    cell?.textLabel.numberOfLines = 0
    return cell!;
}

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
    var height:CGFloat = self.calculateHeightForString(messageArray[indexPath.row])
    return height + 70.0
}

func calculateHeightForString(inString:String) -> CGFloat
{
    var messageString = inString
    var attributes = [UIFont(): UIFont.systemFontOfSize(15.0)]
    var attrString:NSAttributedString? = NSAttributedString(string: messageString, attributes: attributes)
    var rect:CGRect = attrString!.boundingRectWithSize(CGSizeMake(300.0,CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, context:nil )
    var requredSize:CGRect = rect
    return requredSize.height  //to include button's in your tableview

 }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

根据UILabel动态调整uitableViewCell的大小(带段落间距) 的相关文章

  • 小视频播放

    根据我从互联网收集的信息 MPMoviePlayerController 类不支持小视频播放 因此 为了死马当活马医 我想知道可以使用什么样的方法来让小视频在屏幕的一角播放 而不中断屏幕的其余部分 到目前为止 我们已经遇到了两种可行的解决方
  • Objective-C++ 中的 boost::shared_ptr

    这是对我之前提出的一个问题的更好理解 我有以下 Objective C 对象 interface OCPP MyCppobj cppobj end implementation OCPP OCPP init cppobj new MyCpp
  • 将 Xcode 4.5 新 XIB 文件恢复到 iOS<6

    我已经安装了Xcode 4 5 with iOS6 SDK以及其他用于测试目的的旧 SDK 从 4 3 到 6 0 很美 但是有一个BIG问题 生成一个新的 XIB 文件以兼容 iOS6 这是一个问题 因为我的应用程序需要运行在旧设备 不只
  • iOS:我如何知道某个属性是否符合 KVO 标准?

    In the 键值观察编程指南 https developer apple com library archive documentation Cocoa Conceptual KeyValueObserving KeyValueObser
  • Apple 如何在机场菜单打开时更新它? (当 NSMenu 已经打开时如何更改它)

    我有一个状态栏项目 可以弹出一个 NSMenu 并且我有一个委托集 并且它已正确连接 void menuNeedsUpdate NSMenu menu工作正常 也就是说 该方法设置为在显示菜单之前调用 我需要监听该方法并触发异步请求 稍后在
  • 如何用Block简化回调逻辑?

    假设我需要与一个提供协议的类进行通信 并在操作完成时调用委托方法 如下所示 protocol SomeObjectDelegate required void stuffDone id anObject void stuffFailed e
  • NSDateFormatter:根据 currentLocale 的日期,不包含年份

    这不会太难吧 我想显示不带年份的日期 例如 8 月 2 日 美国 或 02 08 德国 它也必须适用于许多其他语言环境 到目前为止 我唯一的想法是对年份进行正常格式 然后从生成的字符串中删除年份部分 我认为你需要看一下 NSString d
  • UITextView:内存使用量巨大

    我在 UITextView 中遇到了内存使用过多的问题 我正在将 50Kb ascii 文本文件加载到 NSString 中 并将其分配给应用程序中空 UITextView 组件的 text 属性 这立即使我的内存占用量增加了 100Mb
  • 为每行 NSTableView 文本着色

    我有一个 NSTableView 它显示我拥有的对象数组 对于每个对象 行 我想根据在每个对象上运行的函数的结果来更改显示的文本的颜色 因此 例如表中存在于另一个列表 或其他一些要求 中的所有对象 我想以绿色文本显示它们 不存在的对象以红色
  • let/var 如何解决可变性? [复制]

    这个问题在这里已经有答案了 我没有任何问题 我只是想对有关可变性的问题进行一些澄清 在 Objective C 中我们会使用例如NSMutableArray得到一个可变数组和NSArray得到一个不可变的 我对两者的内部运作了解不多 但据我
  • AVPlayer 不播放音频 - iOS 9,目标 - C

    我正在尝试从我的应用程序中的 URL 播放音频 iOS 8 中一切都按预期发生 模拟器和物理设备 对于 iOS 9 它可以在模拟器中运行 但在设备上 音频根本无法播放 出现流媒体 如果我单击播放 进度条还显示音频正在加载并播放 但没有声音
  • 选择 UITableViewCell 时 UIView 背景颜色消失

    我在界面生成器中构建了一个简单的 tableViewCell 它包含一个包含图像的 UIView 现在 当我选择单元格时 会显示默认的蓝色选择背景 但 UIView 的背景颜色消失了 我的 UITableViewCell 的实现文件没有做任
  • 如果加载 dylib,垃圾收集工作队列会崩溃

    我们正在将应用程序从 10 6 移植到 10 8 我正在查看我们在应用程序中加载的 dylib 我面临着非常不寻常的崩溃垃圾收集工作队列并附有以下消息 malloc Thread suspend unable to suspend a th
  • 与 Objective-C 的 VPN 连接

    有没有办法在 iPhone 的 Objective C 中以编程方式建立 VPN 连接 有这方面的好教程吗 有人知道吗 多谢 我认为第三方应用程序无法访问这些 API
  • UISlider不会自动重绘

    我的应用程序上有一个 UISlider 有时我不仅需要更新它的值 还需要更新它的minimumValue 值已更改 但如果我调用 setValue 方法或为滑块分配新值 它会具有新值 但滑块不会将自身重新绘制到该新值应有的位置 我怎样才能重
  • 如何为图层阴影不透明度设置动画?

    我有一个视图 我已将 LayerOpacity 设置为 1 theView layer shadowOpacity 1 0 当视图位于屏幕下方时 这看起来很好 当我将此视图向上移动以与另一个有阴影的视图齐平时 它们看起来不太好 有没有办法让
  • 删除分组 UITableView 中的分隔符

    我需要使用自定义单元格创建分组表格视图 每个单元格必须有一个背景图像 以便一个单元格的图像会接触第二个单元格的图像 依此类推 我尝试将分隔符样式设置为 无 但我仍然得到单元格之间的透明分隔符 请帮我删除单元格之间的空间 祝你有美好的一天 谢
  • 带约束的嵌套集合视图的意外行为 (Swift 4)

    我的表格视图中有一个单元格 其中包含水平分页集合视图 该集合视图的每个页面内都有一个垂直集合视图 为了避免 滚动滚动 问题 我在垂直集合视图中禁用了垂直滚动 垂直集合视图的单元格计数不是静态的 可以是任意数字 因此 这会产生一个问题 集合视
  • 在 UITableView 的部分标题文本下方添加一些边距

    我已经设计了标题文本的样式 func tableView tableView UITableView cellForRowAtIndexPath indexPath NSIndexPath gt UITableViewCell let ce
  • 在成为FirstResponder或resignFirstResponder的情况下将对象保持在键盘顶部?

    我目前在键盘顶部有一个 UITextField 当您点击它时 它应该粘在键盘顶部并平滑地向上移动 我不知道键盘的具体时长和动画类型 所以确实很坎坷 这是我所拥有的 theTextView resignFirstResponder UIVie

随机推荐