以编程方式创建的 UITableView 不显示任何内容

UITableView created Programmatically doesn't Show anything

我正在尝试生成具有 table 视图的叠加层,然后将搜索栏添加到列表中 但现在我正在努力创建 table 视图,因为它需要以编程方式完成。

叠加层也能正确显示,但未显示任何条目。 如果我打印出 UITableViewAutomaticDimension 它总是 returns -1 但在调试模式下我可以看到在 cellForRowAt 中定义了单元格并且高度为 46

我自己返回这个高度也没有解决问题

代码:

public class PersonOverlay : UITableView, UITableViewDelegate, UITableViewDataSource {

var overlayView = UIView()
var tableView = UITableView()

let myArray = ["1","2","3","4"]



public func showPersons(view: UIView) -> UITableView {

    //create new opaque view to lay over the Main view
    self.overlayView = UIView(frame: UIScreen.main.bounds)
    self.overlayView.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.8)

    //create a tableview to display possible inputs
    self.tableView.frame = CGRect(x:0,y:0, width:UIScreen.main.bounds.width, height:UIScreen.main.bounds.height/2)
    self.tableView.frame = UIScreen.main.bounds
    self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "PersonCell")
    self.tableView.delegate = self
    self.tableView.dataSource = self

    //add to overlay and afterwards to the view
    self.overlayView.addSubview(self.tableView)
    view.addSubview(self.overlayView)

    DispatchQueue.main.async {
        self.tableView.reloadData()
    }

    return tableView

}

public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    //returns -1 ?
    print(UITableViewAutomaticDimension)
    return UITableViewAutomaticDimension
}

public func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    //view clicked
    print("clicked at index \(indexPath.row)")
}

public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    print("tableview numberofrowsinsection \(myArray.count)")
    return myArray.count
}

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = self.tableView.dequeueReusableCell(withIdentifier: "PersonCell") as! UITableViewCell

    print(String(describing: myArray[indexPath.row] ))
    cell.textLabel?.text = myArray[indexPath.row]

    return cell
}

}

它被另一个调用ViewController显示一些其他信息

我希望任何人都可以帮助并感谢您的宝贵时间:)

在您调用 class 的 ViewController 的 viewDidLoad() 中尝试:

let pOverlayTableView = PersonsOverlay()
self.tableView.registerClass(pOverlayTableView, forCellReuseIdentifier: "PersonCell")