[英]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. 我试图通过使用部分A中的以下代码,根据详细文本标签中设置的内容动态设置行高。
I am inserting few lines of text into a cell's detail text label as shown below in Part B 我将几行文本插入单元格的详细文本标签中,如下面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 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 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. 设置UILabel的约束。 (top, left, bottom, right) Set lines of the UILabel to 0 (上,左,下,右)将UILabel的行设置为0
Add the following code in the viewDidLoad method of the ViewController: 在ViewController的viewDidLoad方法中添加以下代码:
tableView.estimatedRowHeight = 68.0
tableView.rowHeight = UITableViewAutomaticDimension
// Delegate & data source //委托和数据源
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension;
}
Swift 4: 斯威夫特4:
// Delegate & data source //委托和数据源
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
Swift 4.2: 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 给tableview的内部内容提供top,bottom,leading和trailing。使用下面的表视图方法
func tableView(_ tableView: UITableView,heightForRowAt indexPath:IndexPath) -> CGFloat
{
return UITableViewAutomaticDimension
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat
{
return 100
}
tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 100.0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.