【问题标题】:TableView not appearing in simulator?TableView 没有出现在模拟器中?
【发布时间】:2018-09-27 19:01:18
【问题描述】:

我创建了一个带有单视图应用程序模板的 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]))
    }

}

【问题讨论】:

  • 在设备中工作正常吗?
  • 你添加了根视图控制器吗?
  • 你必须为表格视图设置大小

标签: ios swift uitableview ios-simulator viewcontroller


【解决方案1】:

正如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 自动设置的视图的左侧、右侧、顶部和底部设置了约束。这将强制改变高度和宽度,具体取决于您的左侧、右侧、顶部和底部的位置。

【讨论】:

    【解决方案2】:

    tableView 没有框架

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

    或者使用约束

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-23
      • 1970-01-01
      • 2017-12-15
      • 2012-06-09
      相关资源
      最近更新 更多