自动调整uitableviewcell的大小-SWIFT [英] Auto-sizing a uitableviewcell - SWIFT

查看:406
本文介绍了自动调整uitableviewcell的大小-SWIFT的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据UILabel的大小来调整tableviewcell的大小,该大小可以是一行或多行.我需要在应用程序的其余部分中打开自动版式,因此我不想将其关闭以使其正常工作.目标是iOS 7和iOS 8.

I am trying to resize a tableviewcell based on the size of a UILabel that can be one or more lines. I need autolayout turned ON for the rest of the app, so I don't want to turn it off to get this working. Target is iOS 7 and iOS 8.

我尝试了几种解决方案,但是由于某种原因,我似乎无法获得正确的标签高度来自动调整或调整单元格的高度.

I have tried several solutions, but for some reason I can't seem to get the correct height of the label to automatically adjust or to adjust the cell height.

此方法中出现问题:calculateHeightForConfiguredSizingCell.我在Git上放置了一个示例项目,因此您可以看到我所看到的.

The problem is occurring in this method: calculateHeightForConfiguredSizingCell. I have put a sample project on Git, so you can see what I am seeing.

https://github.com/mdaymond/cellResizer

此示例基于本文: http://www.raywenderlich.com/73602/dynamic-table-view-cell-height-auto-layout

更新 我检查了代码的更新.它几乎可以按照我想要的方式工作并以编程方式进行计算,但是由于某种原因,标签高度的尺寸不够正确-无法获得所需的完整高度.原始代码的问题是标签需要显式的宽度.

Update I checked in an update to the code. It's ALMOST working the way I want and calculating programatically, but for some reason the label height isn't quite sized correctly - it's not getting the full height required. Problem with the original code was that the label needed an explicit width.

推荐答案

在这里,如果您支持IOS 7,则需要在类中实现UITableViewDelegate协议,然后重写:

Here we go, if you are supporting IOS 7 then you need to implement UITableViewDelegate protocol in your class and then override:

    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {

}

有关基于标签文本长度的动态自定义UITableViewCell的高度的更多信息(请查看此信息),您可以将代码放在heightForRowAtIndexPath函数中: 基于标签文本长度的高度

for more information about Dynamic custom UITableViewCell's height based on label text length (check this out) and you can place the code in the heightForRowAtIndexPath function: height based on label text length

也可以覆盖:

 func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
       // example to return the estimated height 
        return 280
    }

注意:通过支持IOS 7,您应该手动处理它.没有比iOS 8更简单的方法了.

Note : by supporting IOS 7 you should handle it manually. there is no such easier way as IOS 8.

但是,如果您仅支持IOS 8及更高版本,则可以在下面的两行中简单地做到这一点:

But if you are only supporting IOS 8 and later then you can do it simply in the following two lines :

self.tableView.estimatedRowHeight = 280
self.tableView.rowHeight = UITableViewAutomaticDimension

这篇关于自动调整uitableviewcell的大小-SWIFT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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