【问题标题】:Swift Changing the size of tableview cellsSwift 更改表格视图单元格的大小
【发布时间】:2018-08-25 16:34:21
【问题描述】:

正如标题所说,我正在寻找一种方法来更改我的 tableview 中每个单元格的大小。我有两个问题:

1) 如何在我的表格视图中将所有单元格的大小更改相同的数量?

2) 是否可以根据特定单元格中文本的长度自动调整单元格的大小?

我知道之前已经有人问过类似的问题,但我无法正确实施他们的答案,因为它们已经过时了一段时间。非常感谢您的帮助,在此先感谢您!

【问题讨论】:

    标签: swift uitableview cell


    【解决方案1】:

    1) 要更改所有相同类型的单元格的大小,首先需要创建CellType,这里是如何执行此操作的说明。 https://stackoverflow.com/a/51979506/8417137 或者你可以检查 indexPath.row,但这并不酷:)

    比这里:

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        switch cellType {
        case firstType:
          return firstCellTypeHeight
        case secondType: 
          return secondCellTypeHeight
        default:
          return defaultCellHeight
        }
    }
    

    2) 是的,有可能。你创建你的CustomCell。在你的CustomCell 你应该 在ContentView 中设置您的文本字段或标签。您的文本视图将拉伸您的单元格。

    重要的事情。在上面的方法中,你必须返回这样的特殊高度。

    return UITableViewAutomaticDimension
    

    例如,您的代码将如下所示。

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        switch cellType {
        case firstType:
          return firstCellTypeHeight
        case secondType: 
          return secondCellTypeHeight
        // Your stretching cell
        case textCellType:
          return UITableViewAutomaticDimension
        }
    }
    
    override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        switch cellType {
        case firstType:
          return firstCellTypeHeight
        case secondType: 
          return secondCellTypeHeight
        // Your stretching cell
        case textCellType:
          return UITableViewAutomaticDimension
        }
    }
    

    【讨论】:

    • 有没有办法在不创建新文件的情况下做到这一点?如何使用 indexPath.row 方法更改大小?也感谢您的详细回答!
    • 如果你真的知道你有什么类型的细胞。为了不创建另一个答案,我给你这个链接和截图。 dropbox.com/s/dly1k9ixlrzxq1n/…
    • 好吧,我使用了截图中的功能,单元格放大了,但文本仍然不完全可见。这是单个单元格的样子 dropbox.com/s/hzxbrgxgt8yg3o2/… 抱歉,我只是想解决这个问题:-(
    • 你应该设置你的 textLabel "textLabel.numberOfLines = 0"
    • 很高兴能帮到你! :)
    猜你喜欢
    • 2021-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 2021-09-30
    • 2017-11-29
    相关资源
    最近更新 更多