【发布时间】:2019-01-30 18:06:52
【问题描述】:
我编写了一个代码,用于在我的 TableView 中添加 UIView 数组,但是当我添加它们时,它不会逐行显示它们,而我创建了一个循环,让它在我的 TableView 中添加每个项目,但它添加了它们一个高于另一个,另一种解决方案?
我的视图控制器:
class mainViewController: UIViewController {
private var myArray: [UIView] = []
private var myTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
let barHeight: CGFloat = UIApplication.shared.statusBarFrame.size.height
let displayWidth: CGFloat = self.view.frame.width
let displayHeight: CGFloat = self.view.frame.height
myTableView = UITableView(frame: CGRect(x: 50, y: barHeight, width: displayWidth, height: displayHeight - barHeight))
myTableView.register(UITableViewCell.self, forCellReuseIdentifier: "MyCell")
myTableView.dataSource = self
myTableView.delegate = self
self.view.addSubview(myTableView)
let DoneBut: UIButton = UIButton(frame: CGRect(x: 50, y: 0, width: 150, height: 50))
DoneBut.setTitle("Done", for: .normal)
DoneBut.backgroundColor = UIColor.blue
let DoneBut2: UIButton = UIButton(frame: CGRect(x: 50, y: 0, width: 50, height: 50))
DoneBut2.setTitle("Done2", for: .normal)
DoneBut2.backgroundColor = UIColor.blue
let view1 = UIView()
view1.addSubview(DoneBut)
myArray.append(view1)
let view2 = UIView()
view2.addSubview(DoneBut2)
myArray.append(view2)
}
}
extension mainViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, cellForRowAt indexPath:
IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier:
"MyCell", for: indexPath as IndexPath)
for array in myArray {
cell.contentView.addSubview(array)
}
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection
section: Int) -> Int {
return myArray.count
}
}
extension mainViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath:
IndexPath) {
print("Num: \(indexPath.row)")
print("Value: \(myArray[indexPath.row])")
}
}
【问题讨论】:
-
您为什么要尝试将每个子视图添加到每一行?在任何给定时间,子视图只能位于一个父视图中。
-
首先:您永远不会将视图限制为单元格的内容视图。其次,处理这个问题的最佳方法是制作一个自定义单元格并将子视图添加到单元格类中的单元格中,而不是添加到 tableview 的父级中。
-
我正在制作一个标签栏,我想执行与 IOS 的更多按钮相同的行为,当您单击它时,我认为会出现一个表格视图
-
@KaylaGalway 我知道,但我必须在没有 xib 文件的情况下创建我的 tabBar
-
我不确定你想说什么。也许张贴一张你想要完成的图片。
标签: swift uitableview uibutton