简体   繁体   中英

Dynamically adjust the height of the tableview cell based on content - iOS Swift

I am trying to set the row height dynamically based on the content set in the detail text label, by using the below code in Part A.

I am inserting few lines of text into a cell's detail text label as shown below in Part B

I've looked at other similar questions but none have helped.

Can some one please advice how I can adjust the row height dynamically based on the content of the detail text label.

Part A

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}

Also tried

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

Part B

 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "daysIdentifier", for: indexPath)

        cell.textLabel?.text = days[indexPath.row]

        cell.detailTextLabel?.numberOfLines = 0

        var joinedString            = self.availabilityTimeDict[dayName]?.joined(separator: " \n ")
        cell.detailTextLabel?.text  = joinedString
        return cell
    }

在此输入图像描述

Use custom cell and labels. Set up the constrains for the UILabel. (top, left, bottom, right) Set lines of the UILabel to 0

Add the following code in the viewDidLoad method of the ViewController:

tableView.estimatedRowHeight = 68.0
tableView.rowHeight = UITableViewAutomaticDimension

// Delegate & data source

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return UITableViewAutomaticDimension;
}

Swift 4:

// Delegate & data source

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
     return UITableViewAutomaticDimension
}

Swift 4.2:

// Delegate & data source

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
     return UITableView.automaticDimension
}

give top,bottom,leading and trailing to your lable inside content of tableview.Use below methods of table view

func tableView(_ tableView: UITableView,heightForRowAt indexPath:IndexPath) -> CGFloat
{
 return UITableViewAutomaticDimension
}

func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat
{
 return 100
}
  • 首先设置一个自定义单元格并添加一个标签,并将其行数设置为零,并为单元格的内容视图提供底部,顶部,前导,尾随约束(不要给出高度),同时在viewDidLoad中为单元格大小的单元格提供自定义高度你只需要做,

tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 100.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM