以编程方式创建的TableView不会调用cellForRowAt

时间:2019-08-13 10:41:03

标签: swift uitableview

我有一个实现UITableViewDelegateUITableViewDataSource的类,并且我执行以下代码:

let table = UITableView()        
table.rowHeight = UIScreen.main.bounds.height * 0.125
table.delegate = self
table.dataSource = self
let nib = UINib(nibName: "PrognoseTableViewCell", bundle: Bundle.main)
table.register(nib, forCellReuseIdentifier: "pcell")
table.reloadData()
table.translatesAutoresizingMaskIntoConstraints = false
container.addSubview(table)


NSLayoutConstraint.activate([
    table.trailingAnchor.constraint(equalTo: rightContainer.leadingAnchor),
    table.bottomAnchor.constraint(equalTo: rightContainer.bottomAnchor),
    table.topAnchor.constraint(equalTo: rightContainer.topAnchor),
    table.widthAnchor.constraint(equalToConstant: UIScreen.main.bounds.width * 0.2)
    ])

containerrightContainer是当前ViewController的视图。表格显示正确,只是单元格为空。我的课程实现的函数func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell也没有被调用。 numberOfRowsInSection被调用并返回6。 我想念什么?

1 个答案:

答案 0 :(得分:0)

我试图重现此问题,这是我尝试的事情:

  • 以与您相同的方式在视图控制器中创建表。实现了委托和数据源方法。
    class ViewController : UIViewController,UITableViewDelegate,UITableViewDataSource {

        @IBOutlet weak var rightContainer: UIView!
        @IBOutlet weak var container: UIView!

        override func viewDidLoad() {
            super.viewDidLoad()

            let table = UITableView()
            table.rowHeight = UIScreen.main.bounds.height * 0.125
            table.delegate = self
            table.dataSource = self
            table.backgroundColor = UIColor.red
            let nib = UINib(nibName: "PrognoseTableViewCell", bundle: Bundle.main)
            table.register(nib, forCellReuseIdentifier: "pcell")
            table.reloadData()
            table.translatesAutoresizingMaskIntoConstraints = false
            container.addSubview(table)


            NSLayoutConstraint.activate([
                table.trailingAnchor.constraint(equalTo: rightContainer.leadingAnchor),
                table.bottomAnchor.constraint(equalTo: rightContainer.bottomAnchor),
                table.topAnchor.constraint(equalTo: rightContainer.topAnchor),
                table.widthAnchor.constraint(equalToConstant: UIScreen.main.bounds.width * 0.4)
                ])

            // Do any additional setup after loading the view.
        }


        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return 6
        }

        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "pcell") as! PrognoseTableViewCell
            cell.textLabel?.text = "Test cell"
            return cell
        }
    }

This was the result on running it on a simulator