我试图从另一个类添加UITableView
,但不调用delegate
方法。只有numberOfRowsInSection
方法被调用。我知道我可以在主要的ViewController
中做到这一点,但我想从另一个班级做到这一点。可能吗?此代码功能完全正常,只需复制并粘贴到项目中即可。谢谢!未调用UITableView委托方法。从另一个类创建
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let t = Table()
t.create()
}
}
class Table: UIViewController, UITableViewDelegate, UITableViewDataSource {
private let myArray: NSArray = ["First","Second","Third"]
func create() {
let barHeight = UIApplication.shared.statusBarFrame.size.height
let displayWidth = UIScreen.main.bounds.width
let displayHeight = UIScreen.main.bounds.height
let myTableView = UITableView(frame: CGRect(x: 0, y: barHeight, width: displayWidth, height: displayHeight - barHeight))
myTableView.register(UITableViewCell.self, forCellReuseIdentifier: "MyCell")
UIApplication.shared.delegate?.window??.rootViewController?.view.addSubview(myTableView)
myTableView.dataSource = self
myTableView.delegate = self
myTableView.backgroundColor = UIColor.red
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("Num: \(indexPath.row)")
print("Value: \(myArray[indexPath.row])")
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print("numberOfRowsInSection")
return myArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
print("cellForRowAt")
let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath as IndexPath)
cell.textLabel!.text = "\(myArray[indexPath.row])"
return cell
}
}
是TableView中看到你的屏幕? – CodeChanger
缺少'reloadData()'也许? – Larme
是的,表格视图在屏幕上可见,但委托方法没有响应。 reloadData()没有帮助。 – Joe