【问题标题】:UITableView with 3 custom views and dynamic height具有 3 个自定义视图和动态高度的 UITableView
【发布时间】:2016-11-11 20:34:28
【问题描述】:

我在做什么

我正在使用 swift3 开发一个 IOS 应用程序(来自现有的 android 版本)。 我有一个 UITableView 可以有 3 种类型的视图(作为单元格)。一种类型是标题,另一种代表不同的类型(小时、照片或/和材料)。 请看下一张图片以阐明架构:

我尝试了什么

经过几天的研究,我尝试了很多可能的解决方案。这些是最好的意图:

  • 具有不同视图的静态行:

https://stackoverflow.com/a/30776750/2131420 这不是一个解决方案,因为视图的数量是静态的,我不能有随机的视图顺序(如果顺序不同,应用程序崩溃......首先是视图 2,接下来是视图 1,然后再次查看 2.. .)

  • 一个包含所有视图类型的视图:

目前,这是最好的尝试...这包括绘制一个包含 3 种视图类型的视图。每种视图类型都有一个 UIView(如容器)。 然后,使用代码,使用不必要的 UIView(容器)将视图的高度设置为 0。 这种方法的问题是单元格的自动尺寸。研究,我比你可以将 NSLayoutConstraints 设置为 0 来隐藏。但是,如果你这样做,文本会被三个点截断(...)我不能这样做。另外,我尝试将属性 lineBrake 设置为“WordWrap”并将行设置为 0。这也不能解决问题。 图片示例:

问题

如何根据数组中的值将不同的视图加载到单元格中?以及如何根据内容的高度设置这个单元格的高度?

抱歉英语不好,提前致谢!

【问题讨论】:

    标签: ios iphone swift uitableview swift3


    【解决方案1】:

    既然你想要动态单元格,我会首先为每个单元格制作 3 个 xib,每个单元格都有自己的类,因为它们显示不同的视图并且彼此具有不同的模型。

    确保单元格内的项目约束是可调整的,并且 - 仅当您的应用支持 iOS 7 之前的版本时 - 在 tableView:heightForRowAtIndexPath: 中返回固定大小。
    Heres an easy tutorial to help you understand them better.

    你应该实现UITableView委托方法

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

    另外,实现tableView:estimatedHeightForRowAtIndexPath: 以便为 UITableView 提供单元格的估计大小。

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

    UITableView委托方法中

            func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
                 if indexPath.row == 0 {
                   //Show your first cell
                 }else if (model[indexPath.row].type == 1) { //or another way to distinguish from third cell
                  //Show your second cell
                 }else {
                  //Show your third cell
                 }
     }
    

    不要忘记在 viewDidLoad() 中将自定义单元格添加到 UITableView

    @IBOutlet weak var tableView: UITableView!
    
        override func viewDidLoad() {
    self.tableView.register(UINib(nibName: "FirstCell",bundle: nil), forCellReuseIdentifier: "FirstCell")
    self.tableView.register(UINib(nibName: "SecondCell",bundle: nil), forCellReuseIdentifier: "SecondCell")
    self.tableView.register(UINib(nibName: "ThirdCell",bundle: nil), forCellReuseIdentifier: "ThirdCell")
    }
    

    【讨论】:

    • 太棒了!这是做到这一点的方法!谢谢!
    猜你喜欢
    • 1970-01-01
    • 2015-09-17
    • 1970-01-01
    • 1970-01-01
    • 2020-02-07
    • 2011-11-27
    • 2013-12-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多