繁体   English   中英

TableView没有出现在模拟器中?

[英]TableView not appearing in simulator?

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

蓝色导航栏,但空白的白色背景

我认为问题一定出在tableView的子视图上,但是我不清楚如何解决该问题。 (我没有使用情节提要,但将在某个时候实现启动屏幕。这样可以解决我的问题吗?)

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没有框架

tableView = UITableView()

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

或使用约束

正如Sh_Khan所说,您需要做的是设置一个框架。 如果这是您的永久方法,则也可以设置约束。 如果设置约束,它将自动更改高度和宽度。

tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
tableView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true

您可以将此代码添加到viewDidLoad函数中。 基本上,它为UIViewController自动设置的视图的左侧,右侧,顶部和底部设置了约束。 这将迫使高度和宽度根据左侧,右侧,顶部和底部的位置而改变。

暂无
暂无

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

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