UITableView in Swift

前端 未结 17 1384
滥情空心
滥情空心 2020-12-04 08:09

I\'m struggling to figure out what\'s wrong with this code snippet. This is currently working in Objective-C, but in Swift this just crashes on the first line of the method.

17条回答
  •  执笔经年
    2020-12-04 08:15

    Well, I have done this way:

    Steps for UITableView using Swift:

    • Take UITableView in ViewController
    • Give Referencing Outlets in ViewController.swift class
    • Give Outlets dataSource & delegate to ViewController

    Now Swift code in ViewController.swift class:

    class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
        @IBOutlet weak var mTableView: UITableView!
    
        var items: [String] = ["Item 1","Item 2","Item 3", "Item 4", "Item 5"]
    
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.
    
            self.mTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
        }
    
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }
    
        func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return self.items.count;
        }
    
        func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
            var cell:UITableViewCell = self.mTableView.dequeueReusableCellWithIdentifier("cell") as! UITableViewCell
    
            cell.textLabel?.text = self.items[indexPath.row]
             println(self.items[indexPath.row])
    
            return cell
        }
    
        func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
            println("You have selected cell #\(indexPath.row)!")
        }
    }
    

    Now it's time to Run your program.

    Done

提交回复
热议问题