繁体   English   中英

无法在我的ViewController中显示tableview

[英]Can't show tableview in my ViewController

我需要一个简单UITableView 1行6列,我想创建一个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)
    }
}

您忘记为tableView设置数据源

添加:mTableView.dataSource = self

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM