gpt4 book ai didi

ios - 如何使用 Swift 创建具有动态单元格高度的静态单元格

转载 作者:搜寻专家 更新时间:2023-10-30 21:49:07 25 4
gpt4 key购买 nike

我看过几个介绍如何设置动态单元格高度的教程,但所有这些教程都只在您通过设置适当的约束并使用 UITableViewAutomaticDimension 使用动态单元格时显示。但是,我想对静态单元格执行此操作。

我的应用程序中有一个 TableView Controller ,其中包含多个单元格,这些单元格显示一个带有披露指示器的类别,其中有一个标题,然后是一个描述,描述文本的大小各不相同。因此,我希望单元格的高度根据描述文本的大小是动态的。

我使用静态单元格而不是动态单元格的原因是因为在类别单元格上方我有一些单元格,其中包含一些只能通过使用静态单元格和 Storyboard才能获得的设计。

我正在使用 iOS9Xcode 7.3Swift 2.2

更新

TableView Controller 代码

import UIKit

class CategoriesTableViewController: UITableViewController {

override func viewDidLoad() {
super.viewDidLoad()

tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 140
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

// MARK: - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 2
}

}

更新 2

根据下面接受的答案,我将下面的两种方法添加到我的 TableView Controller 中,并删除了我在 viewDidLoad() 中的 2 行。这是为我做的!请记住,我必须确保每个单元格中的所有标签都使用顶部、底部、前导和尾随约束。此外,每个标签的行数必须设置为 0。

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

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

最佳答案

UILabel:

通过编程方式设置 numberOfLines = 0 或在 UILabel 的属性检查器中将行设置为零。

enter image description here

UITextView:

让我们选择您的 TextView 并取消选中启用的滚动,如下图所示。

enter image description here

将以下代码添加到您的 View Controller :

swift 5:

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

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

swift 2.2:

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

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

关于ios - 如何使用 Swift 创建具有动态单元格高度的静态单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38778849/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com