如何以编程方式将UITableView添加到UIStackView中?

时间:2017-01-30 01:21:44

标签: ios uitableview swift3 uistackview

我创建了这段代码来测试UIStackViews中的tableViews:

这是tableView文件:

import UIKit

class Table: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var items:[String] = ["alpha", "betha", "gama", "delta"]

    lazy var tableView:UITableView = {
        let tb = UITableView(frame: self.view.bounds, style: .grouped)
        tb.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        tb.delegate = self
        tb.dataSource = self
        tb.register(UITableViewCell.self, forCellReuseIdentifier:"cell")
        return tb
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.addSubview(self.tableView)
    }

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        let item = self.items[(indexPath as NSIndexPath).item]
        cell.textLabel?.text = "\(item)"
        return cell
    }
}

这是我的MainViewController StacktableView

import UIKit

class Main: UIViewController {

    lazy var table:Table = { return Table() }()

    lazy var mainStack: UIStackView = {
        let s = UIStackView()
        s.axis = .vertical
        s.alignment = .center
        s.distribution = .equalCentering
        s.spacing = 0
        s.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        s.addArrangedSubview(UIView())
        s.addArrangedSubview(self.table.view)
        s.addArrangedSubview(UIView())
        return s

    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.addSubview(self.mainStack)
    }

}

在我的委托中,如果我将Table类用作rootViewController,一切正常:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        self.window = UIWindow(frame: UIScreen.main.bounds)
        let table = Table()
        let nav = UINavigationController(rootViewController: table)
        self.window!.rootViewController = nav
        self.window!.backgroundColor = UIColor.white
        self.window!.makeKeyAndVisible()
        return true
    }

但是,如果我使用主类,则不会显示任何内容:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        self.window = UIWindow(frame: UIScreen.main.bounds)
        let main = Main()
        let nav = UINavigationController(rootViewController: main)
        self.window!.rootViewController = nav
        self.window!.backgroundColor = UIColor.white
        self.window!.makeKeyAndVisible()
        return true
    }

我做错了什么?

0 个答案:

没有答案