我有带有动态单元格的 UITableView
。在 viewDidLoad
中,我有 NSURLSession
,它将一些数据下载到公共(public)变量 someDataArray: [NSString]
。我在我的单元格中使用 AutoLayout 和 UILabel 具有类似 this 的约束.加载 View 时,我希望看到所有单元格的大小相同(例如:100)。但是,当点击单元格时,我想将此单元格的高度更改为 UIlabel
框架的高度大小
所以我的代码看起来像:
class someVC: UIViewController, UITableViewDelegate
{
var someDataArray: [NSString] = []
var cellTapped = 0
override func viewDidLoad() {
//NSURLSession download to someDataArray[]
}
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!
{
let cell = self.table.cellForRowAtIndexPath(indexPath) as customCellVC
cell.someTextView.text = someDataArray[indexPath.row]
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let cell = self.table.cellForRowAtIndexPath(indexPath) as customCellVC
if(cellTapped == 0) {
cellTapped = 1
table.beginUpdates()
table.endUpdates()
} else {
cellTapped = 0
table.beginUpdates()
table.endUpdates()
}
}
func tableView(tableView: UITableView!, heightForRowAtIndexPath indexPath: NSIndexPath!) -> CGFloat
{
// heightForRowAtIndexPath call first, how to calculate the size of frame uilabel? When it's tapped or not
// how to make all UILabel one size by load but sizetofit by tap on it?
}
}
最佳答案
您可以使用自动布局来计算行的高度。看看这个:
https://github.com/smileyborg/TableViewCellWithAutoLayoutiOS8
或者:(所以我解决了这个问题,因为它更符合我的要求)是:
计算标签的高度:
func getLabelHeight(mytext: String, fontSize: CGFloat, width: CGFloat)->CGFloat {
let font = UIFont.systemFontOfSize(fontSize)
let size = CGSizeMake(width,CGFloat.max)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = .ByWordWrapping;
let attributes = [NSFontAttributeName:font,
NSParagraphStyleAttributeName:paragraphStyle.copy()]
var text = mytext as NSString
let rect = text.boundingRectWithSize(size, options:.UsesLineFragmentOrigin, attributes: attributes, context:nil)
return rect.size.height
}
这将返回计算出的特定宽度的标签高度。因此,您可以在 ViewDidLoad 上进行计算(第一次并将其设置为以 Indexpath.row 作为索引的字典),然后将此值用于“heightForRowAtIndexPath”。因此您也可以重新加载您的特定单元格(使用新的高度)
然后您仍然可以使用“SizeToFit”宽度指定特定的标签宽度。
关于ios - 来自 NSURLSession 的动态数据的单元格行的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26037146/