无法使用多行标签在表视图中自动调整单元格

jwi*_*tos 2 uitableview ios swift

我正在尝试使用多行标签来制作表格视图.不幸的是,我没有运气 - 细胞似乎根本没有调整大小,虽然我得到多线标签.

我的TableViewController的Swift代码:

import UIKit

class QuestionsController: UITableViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.estimatedRowHeight = 100.0
        tableView.rowHeight = UITableViewAutomaticDimension
    }

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

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

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("QuestionCell", forIndexPath: indexPath) as! BasicQuestionCell
        let question = questionsData[indexPath.row] as Question
        cell.titleLabel.text = question.content
        return cell
    }
}
Run Code Online (Sandbox Code Playgroud)

结果:

我的代码的结果

iOS*_*MIB 7

正如你没有提到的那样,如果你使用的是自动布局,我假设你正在使用自动布局,并对单元格内的标签给出了必要的约束.

现在只需从viewDidLoad()中删除以下两行:

tableView.estimatedRowHeight = 100.0
tableView.rowHeight = UITableViewAutomaticDimension
Run Code Online (Sandbox Code Playgroud)

添加默认功能如下追求它:

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

   return tableView.rowHeight

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

   return UITableViewAutomaticDimension
}
Run Code Online (Sandbox Code Playgroud)

结果:

在此输入图像描述