我試圖從另一個類添加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