UITableViewCell的Swift自动高度

mr_*_*777 1 uitableview ios swift

我试图在基本单元格中创建一个带有大文本的表.表位于UIVIewController中,它实现了Delegate和DataSource.

这是我的ViewController:

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

let answers = ["Swift is a multi-paradigm, compiled programming language created by Apple Inc. for iOS, OS X, and watchOS development. Swift is designed to work with Apple's Cocoa and Cocoa Touch frameworks and the large body of existing Objective-C code written for Apple products. Swift is intended to be more resilient to erroneous code than Objective-C, and also more concise. "]

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

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 1
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("basic", forIndexPath: indexPath) as! UITableViewCell

    cell.textLabel?.numberOfLines = 0
    cell.textLabel?.lineBreakMode = .ByWordWrapping
    cell.textLabel?.text = answers[indexPath.row]
    return cell
}

}
Run Code Online (Sandbox Code Playgroud)

我设置了.numberOfLines = 0,但结果,我只有2行:在此输入图像描述

我怎么解决它?我听说在IOS 8中它比IOS <8更容易,我不需要tableView.heightForRowAtIndexPath.但如果我需要,如何实现它更简单?

也许我需要为我的细胞设置约束?但它是一个基本的细胞.

win*_*rrr 6

如果你希望你的单元格根据其内容自动改变大小,你应该看看这个关于堆栈溢出的类似问题的这个非常好的答案.

从提到的帖子:

在iOS 8中,Apple已经内置了以前必须在iOS 8之前实现的大部分工作.为了使自行调整单元机制能够工作,必须首先将表视图上的rowHeight属性设置为常量UITableViewAutomaticDimension.然后,您只需通过将表视图的estimatedRowHeight属性设置为非零值来启用行高估计,例如:

self.tableView.rowHeight = UITableViewAutomaticDimension;
self.tableView.estimatedRowHeight = 44.0; // set to whatever your "average" cell height is
Run Code Online (Sandbox Code Playgroud)