首页 > 解决方案 > 以编程方式添加 UIView 和 UITableView

问题描述

我正在尝试做到这一点,如第一张图片所示:

图 1

图 2

但不知何故,视图并没有像我想要的那样出现。在这里你可以看到我的完整项目代码:

import UIKit
import RealmSwift
import CVCalendar

class Test: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var myTableView: UITableView  =   UITableView()
    var itemsToLoad: [String] = ["One", "Two", "Three"]
    var myView = UIView()

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = UIColor(red: 4/255, green: 4/255, blue: 4/255, alpha: 1.0)
        self.navigationController?.navigationBar.barStyle = .black
        self.navigationController?.navigationBar.tintColor = UIColor.white
        self.navigationItem.title = "Test"
        self.navigationController?.navigationBar.prefersLargeTitles = true
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        // Get main screen bounds
        let screenSize: CGRect = UIScreen.main.bounds
        let screenWidth = screenSize.width
        let screenHeight = screenSize.height

        myView.frame = CGRect(x: 0, y: 0, width: screenWidth, height: 150)
        myView.backgroundColor = .black
        self.view.addSubview(myView)



        myTableView.frame = CGRect(x: 0, y: 50, width: screenWidth, height: screenHeight-50);
        myTableView.dataSource = self
        myTableView.delegate = self
        myTableView.backgroundColor = .blue
        myTableView.layer.borderWidth = 3

        myTableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")

        self.view.addSubview(myTableView)

    }



    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return itemsToLoad.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

        cell.textLabel?.text = self.itemsToLoad[indexPath.row]

        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("User selected table row \(indexPath.row) and item \(itemsToLoad[indexPath.row])")
    }
}

为什么不会出现?第一张图是我想要的样子,第二张图是现在的样子。

标签: iosswiftxcodeuitableviewuiview

解决方案


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

        if self.itemsToLoad[indexPath.row] != nil {
              cell.textLabel?.text = self.itemsToLoad[indexPath.row]
              cell.backgroundColor = .white

         }else {
               cell.backgroundColor = .blue

            }

        return cell
    }

推荐阅读