Tuesday, August 4, 2015

registerNib - Create UITableView programmatically with a custom XIB file as the prototype cell

1.  Add a new file. Select UITableViewCell as subclass. Select 'Also create XIB file'.

2. Edit the XIB file as the prototype cell.

3. Control-drag the labels to the MyTableViewCell.swift:

import UIKit

class MyTableViewCell: UITableViewCell {

    @IBOutlet weak var myString1: UILabel!
    
    @IBOutlet weak var myString2: UILabel!
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
    

}


4. Complete the file ViewController.swift as below:

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        var myTableView = UITableView(frame: self.view.bounds, style: UITableViewStyle.Plain)
        myTableView.dataSource = self
        myTableView.delegate = self
        
        myTableView.backgroundColor = UIColor.whiteColor()
        
        myTableView.frame = CGRectMake(20, 50, 250, 400)//Optional for table size
        
        myTableView.registerNib(UINib(nibName: "MyTableViewCell", bundle: nil), forCellReuseIdentifier: "myIdentifier")
        
        self.view.addSubview(myTableView)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 5
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let myCell = tableView.dequeueReusableCellWithIdentifier("myIdentifier") as! MyTableViewCell
        myCell.myString1.text = "Row \(indexPath.row)"
        myCell.myString2.text = "String \(indexPath.row)"
        return myCell
    }
    

}

5. Run the app and get this result:


No comments:

Post a Comment