Create UITableView programmatically in Swift

前端 未结 8 1311
青春惊慌失措
青春惊慌失措 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:46

    It makes no sense that you are using a UITableViewController as the data source and delegate for your view controller's table view. Your own view controller should be the table view's data source and delegate.

    Since you seem to want a view controller with a table view that doesn't take up the entire view, move every thing to your view controller as follows:

    ViewController.swift:

    import UIKit
    
    class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            let tableView: UITableView = UITableView()
            tableView.frame = CGRect(x: 10, y: 10, width: 100, height: 500)
            tableView.dataSource = self
            tableView.delegate = self
    
            self.view.addSubview(tableView)
        }
    
        func numberOfSectionsInTableView(tableView: UITableView) -> Int {
            NSLog("sections")
            return 2
        }
    
        func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            NSLog("rows")
            return 3
        }
    
        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
        }  
    }
    

提交回复
热议问题