gpt4 book ai didi

ios - 具有 3 个自定义 View 和动态高度的 UITableView

转载 作者:搜寻专家 更新时间:2023-11-01 07:18:24 27 4
gpt4 key购买 nike

我在做什么

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

enter image description here

我尝试了什么

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

  • 具有不同 View 的静态行:

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

  • 包含所有 View 类型的一个 View :

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

问题

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

抱歉英文,提前致谢!

最佳答案

由于您需要动态单元格,我会首先为每个单元格制作 3 个 xibs,每个单元格都有自己的类,因为它们显示不同的 View 并且彼此具有不同的模型。

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

你应该实现UITableView委托(delegate)方法

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

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

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

UITableView委托(delegate)方法中

        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")
}

关于ios - 具有 3 个自定义 View 和动态高度的 UITableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40555771/

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