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

时间:2018-02-12 13:19:49

标签: ios swift cocoa-touch

我尝试使用表格视图生成叠加层,然后将搜索栏添加到列表中 但是现在我正在努力创建表视图,因为它需要以programmaticaly方式完成。

叠加也正确显示,但没有显示任何声明。 如果我打印出UITableViewAutomaticDimension它总是返回-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调用它显示一些其他信息

我希望任何人都可以帮助和欣赏你的时间:)

1 个答案:

答案 0 :(得分:0)

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

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