无法在我的ViewController中显示tableview

时间:2018-10-26 14:37:30

标签: ios swift uitableview

我需要一个1行6列的简单UITableView,我正在尝试以编程方式创建一个UITableView并将其添加到我的ViewController上,但是没有运气,我看到了一些教程,但我并没有真正弄错我在做什么。也许你们看一下就可以告诉我。 这是我的代码:

class MainVC: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var mTableView: UITableView = {

        //STACKOVERFLOW *In the first line, I'm just positioning it randomly to see if I can get the table view to show, will change later.*
        var tableView = UITableView(frame: CGRect(x: 100, y: 100, width: 100, height: 100), style: .plain)
        tableView.backgroundColor = .red

        tableView.translatesAutoresizingMaskIntoConstraints = false
        return tableView

    }()

    override func viewDidLoad() {

        super.viewDidLoad()
        view.backgroundColor = UIColor(red: 80/255, green: 135/255, blue: 179/255, alpha: 1.0)

        setupNavBar()
        self.navigationItem.searchController = mSearchBarController

        setupMainWeatherIcon()
        setupTableView()

        mTableView.dataSource = self
        mTableView.delegate = self

    }

    private func setupTableView(){

        self.view.addSubview(mTableView)


        mTableView.leadingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leadingAnchor).isActive = true
        mTableView.trailingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.trailingAnchor).isActive = true
        mTableView.centerXAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.centerXAnchor).isActive = true
        mTableView.centerYAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.centerYAnchor).isActive = true

    }

    // MARK: TABLE VIEW METHODS!
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        return tableView.dequeueReusableCell(withIdentifier: "forecastCell", for: indexPath)
    }
}

1 个答案:

答案 0 :(得分:1)

您忘记为tableView设置数据源

添加:mTableView.dataSource = self

UITableViewController会自动添加,而UIViewController不会。

您还忘记设置高度锚点和宽度。或顶部和底部锚点

相关问题