ios - TableView 没有出现在模拟器中?

标签 ios swift uitableview ios-simulator viewcontroller

我已经使用单 View 应用程序模板创建了一个 iOS 应用程序。运行应用程序后,启动屏幕会出现大约 2 秒,然后显示蓝色导航栏,但背景为空白。

blue navbar, but a blank white background .

我认为问题一定出在 tableView 的 subview 上,但我不清楚如何解决这个问题。 (我没有使用 Storyboard,但会在某个时候实现开始屏幕。这会解决我的问题吗?)

import UIKit

struct Question {
    var questionString: String?
    var answers: [String]?
    var selectedAnswerIndex: Int?
}

class QuestionController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    let cellId = "cellId"
    let headerId = "headerId"
    var tableView: UITableView?

    static var questionsList: [Question] = [Question(questionString: "What is your favorite type of food?", answers: ["Sandwiches", "Pizza", "Seafood", "Unagi"], selectedAnswerIndex: nil), Question(questionString: "What do you do for a living?", answers: ["Paleontologist", "Actor", "Chef", "Waitress"], selectedAnswerIndex: nil), Question(questionString: "Were you on a break?", answers: ["Yes", "No"], selectedAnswerIndex: nil)]

    override func viewDidLoad() {
        super.viewDidLoad()

        navigationItem.title = "Question"

        navigationController?.navigationBar.tintColor = UIColor.white
        navigationItem.backBarButtonItem = UIBarButtonItem(title: "Back", style: .plain, target: nil, action: nil)

        tableView = UITableView()
        tableView?.dataSource = self
        tableView?.delegate = self
        self.view.addSubview(self.tableView!)
        tableView?.register(AnswerCell.self, forCellReuseIdentifier: cellId)
        tableView?.register(QuestionHeader.self, forHeaderFooterViewReuseIdentifier: headerId)

        tableView?.sectionHeaderHeight = 50
        tableView?.tableFooterView = UIView()
    }

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

        if let index = navigationController?.viewControllers.index(of: self) {
            let question = QuestionController.questionsList[index]
            if let count = question.answers?.count {
                return count
            }
        }

        return 1
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath as IndexPath) as! AnswerCell
        if let index = navigationController?.viewControllers.index(of: self) {
            let question = QuestionController.questionsList[index]
            cell.nameLabel.text = question.answers?[indexPath.row]
        }

        return cell
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: headerId) as! QuestionHeader

        if let index = navigationController?.viewControllers.index(of: self) {
            let question = QuestionController.questionsList[index]
            header.nameLabel.text = question.questionString
        }

        return header
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        if let index = navigationController?.viewControllers.index(of: self) {
            QuestionController.questionsList[index].selectedAnswerIndex = indexPath.item

            if index < QuestionController.questionsList.count - 1 {
                let questionController = QuestionController()
                navigationController?.pushViewController(questionController, animated: true)
            } else {
                let controller = ResultsController()
                navigationController?.pushViewController(controller, animated: true)
            }
        }
    }

}

class ResultsController: UIViewController {

    let resultsLabel: UILabel = {
        let label = UILabel()
        label.text = "Congratulations, you'd make a great Ross!"
        label.translatesAutoresizingMaskIntoConstraints = false
        label.textAlignment = .center
        label.font = UIFont.boldSystemFont(ofSize: 14)
        return label
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Done", style: .plain, target: self, action: Selector(("done")))

        navigationItem.title = "Results"

        view.backgroundColor = UIColor.white

        view.addSubview(resultsLabel)
        view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": resultsLabel]))
        view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": resultsLabel]))

        let names = ["Ross", "Joey", "Chandler", "Monica", "Rachel", "Phoebe"]

        var score = 0
        for question in QuestionController.questionsList {
            score += question.selectedAnswerIndex!
        }

        let result = names[score % names.count]
        resultsLabel.text = "Congratulations, you'd make a great \(result)!"
    }

    func done() {
        navigationController?.popToRootViewController(animated: true)
    }

}

class QuestionHeader: UITableViewHeaderFooterView {

    override init(reuseIdentifier: String?) {
        super.init(reuseIdentifier: reuseIdentifier)
        setupViews()
    }

    let nameLabel: UILabel = {
        let label = UILabel()
        label.text = "Sample Question"
        label.font = UIFont.boldSystemFont(ofSize: 14)
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()

    func setupViews() {
        addSubview(nameLabel)
        addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-16-[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": nameLabel]))
        addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": nameLabel]))
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

class AnswerCell: UITableViewCell {

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupViews()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    let nameLabel: UILabel = {
        let label = UILabel()
        label.text = "Sample Answer"
        label.font = UIFont.systemFont(ofSize: 14)
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()

    func setupViews() {
        addSubview(nameLabel)
        addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-16-[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": nameLabel]))
        addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": nameLabel]))
    }

}

最佳答案

tableView没有frame

tableView = UITableView()

tableView.frame = self.view.bounds  // this for a test change it as you want 

或者使用约束

关于ios - TableView 没有出现在模拟器中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49884406/

相关文章:

iOS - 取消突出显示 UITableViewCell 中的 UIBarButtons?

ios - 将数据传递到另一个 View Controller ,使用自定义结构数据类型,需要初始化程序?

ios - 如何创建一个可以适应其子项不断变化的大小的 ScrollView

iOS swift 如何更改英语以外的基本语言

ios - 通过 Firebase 从 MapKit 注释转至 UITableViewCell

iphone - iOS 中的图像网格

ios - iOS 中的触摸事件传播

ios - willTransitionToState (UITableViewCell) 在某些情况下不被调用

ios - 如何以编程方式在我的选项卡栏 Controller 下添加 UIView?

ios - 快速切换到 UITableViewController 时出现黑屏