我正在尝试创建一个框架,我更喜欢代码中的所有内容,所以我想出了一种方法,除了我面临的主要问题是我不能把数据放在我的表中因为{{1}没有被召唤。
我已设置cellForRowAtIndexpath
和delegate
。
我添加了dataSource
,它返回10.
我添加了numberOfRowsInSection
,它返回10.
我已添加heightForRowAtIndexPath
并返回一个单元格。
主要问题是所有这些其他方法都被调用,因为我在除cellForForAtIndexPath
之外的所有方法中都添加了print语句。
问题是我甚至无法尝试调试,因为甚至没有调用该方法。
cellForForAtIndexPath
我这样使用它是因为我想从另一个类调用class PopControl: NSObject, UITableViewDataSource, UITableViewDelegate {
let tableView = UITableView()
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("row selected")
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
print("cell for row at index path called")
let cell = UITableViewCell()
cell.textLabel?.text = "ABCD"
cell.detailTextLabel?.text = "EFGH"
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print("number of rows in section called")
return 10
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
print("Height for row at index path called")
return 10
}
func makeTable(){
let vc = UIApplication.shared.keyWindow?.rootViewController?.childViewControllers.last
vc?.view.backgroundColor = UIColor.black
print(vc)
tableView.dataSource = self
tableView.delegate = self
vc?.view.addSubview(tableView)
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.topAnchor.constraint(equalTo: (vc?.view.topAnchor)!, constant: 100).isActive = true
tableView.bottomAnchor.constraint(equalTo: (vc?.view.bottomAnchor)!, constant: -20).isActive = true
tableView.leftAnchor.constraint(equalTo: (vc?.view.leftAnchor)!, constant: 20).isActive = true
tableView.rightAnchor.constraint(equalTo: (vc?.view.rightAnchor)!, constant: -20).isActive = true
print("dataSource for tableView is")
print(tableView.dataSource.debugDescription.description)
print("delegate is")
print(tableView.delegate.debugDescription.utf8CString)
}
函数。我的意思是我无意将此课程用作makeTable()
或UIViewController
。我只是想用它来向视图控制器提供代码中任何地方的表格视图。
一切正常但UITableViewController
未被调用。我的意思是tableView被渲染但没有显示单元格。
答案 0 :(得分:0)
问题可能不是重复使用单元格,尝试重用 UITableviewCell
在makeTable
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
在cellForRowAt
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// create a new cell if needed or reuse an old one
let cell:UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier:"Cell") as UITableViewCell!
// set the text from the data model
cell.textLabel?.text = "ABC"
return cell
}