【发布时间】:2018-07-20 12:31:27
【问题描述】:
我正在尝试在 xib 中创建一个动态 UITableView,所以我认为可能可行的是将表格视图放在空白 UIView 中。然后我会继承这个 UIView 并使其遵守协议UITableViewDelegate 和UITableViewDataSource。有人可以指导我吗,因为我尝试了很多东西,但都没有奏效。非常感谢!
编辑:
我会告诉你我之前尝试过的(抱歉,没有原始代码):
class TableControllerView: UIView, UITableViewDelegate, UITableViewDataSource {
let tableView = UITableView()
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
tableView.frame = self.frame
tableView.delegate = self
tableView.dataSource = self
}
func tableView(...cellForRowAt...) {
let cell = UITableViewCell(style: .default, reuseIdentifier: nil)
cell.titleLabel?.text = "test title"
return cell
}
}
但在这种情况下,表格视图最终太大并且与视图不对齐,即使我将它的框架设置为与视图相同
编辑 2:
我的代码现在看起来像这样:
class PharmacyTableView: UIView, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var pharmacyTableView: UITableView!
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//PROVISOIRE depends on user [medications].count
return 2
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .subtitle, reuseIdentifier: nil)
cell.textLabel?.text = "text label test"
cell.detailTextLabel?.text = "detail label test"
return cell
}}
表视图已初始化,但仅在高度锚受到约束时才显示,这是我不想要的,因为它可能会根据用户数据而增长或缩小。我想我会在解决这个问题后完成? 附言: 另外,非常感谢那些花时间帮助我的人:)
编辑 3:
所以,我已将表格视图的类更改为:
class IntrinsicResizingTableView: UITableView {
override var contentSize:CGSize {
didSet {
self.invalidateIntrinsicContentSize()
}
}
override var intrinsicContentSize: CGSize {
self.layoutIfNeeded()
return CGSize(width: UIViewNoIntrinsicMetric, height: contentSize.height)
}
}
现在一切正常!终于!
【问题讨论】:
-
您能告诉我们您尝试过的方法以及您面临的具体问题吗?
-
您到底希望达到什么目标?为什么要在 xib 中创建动态 tableview?
-
那么为什么不将表格视图添加到 xib 本身而不是以编程方式进行
-
我现在已将它添加到情节提要中并通过插座连接它,但我需要以编程方式填充它
标签: ios swift uikit tableview xib