Create UITableView programmatically in Swift

前端 未结 8 1304
青春惊慌失措
青春惊慌失措 2020-12-12 12:00

I try to implement UITableView programmatically without use of xib or Storyboards. This is my code:

ViewController.swift

import UIKi         


        
8条回答
  •  旧巷少年郎
    2020-12-12 12:54

    You don't need to make a separate class for UITableView. Just in your ViewController class implement protocols of UITableViewDelegate and UITableViewDataSource and then implement delegate methods. I think your code should be like

    class ViewController: UIViewController , UITableViewDelegate , UITableViewDataSource {
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            let table: UITableViewController = MyTableViewController()
            let tableView: UITableView = UITableView()
            tableView.frame = CGRect(x: 10, y: 10, width: 100, height: 500)
            tableView.dataSource = table
            tableView.delegate = table
    
            self.view.addSubview(tableView)
        }
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
            NSLog("sections")
            return 2
        }
    
        override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            NSLog("rows")
            return 3
        }
    
        override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
            NSLog("get cell")
            let cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "Cell")
            cell.textLabel!.text = "foo"
            return cell
        } 
    }
    

    Tell us more info or show logs if you still face issue.

提交回复
热议问题