The aim of this post is to show how to build a Custom SWIFTed TableViewCell view cell. I have found several shallow examples with the default cell. But soon you will discover that will not fit a real sample project situation. I have found several difficulties from moving to Swift, that took me more time than I expected and that pushed me also to write this post.
The custom table view cell
I have just created a new Single View Project Application in the default view controller and added a new NSObject class that extends from uitableviewcell.
The storyboard
I have added a table view controller and a tableview cell with an image view and a label.
Now is time to setup the custom table view cell. Firstly the new class associated to the cell:
And secondly set the cell identifier:
The View Controller
Now it is time for connecting the storyboard with the source code. Lets start off with the main view controller:
import UIKit class ViewController: UIViewController, UITableViewDataSource,UITableViewDelegate { @IBOutlet weak var tbvData: UITableView! var items: [String] = ["We dkfj ld flkasjlfasjlkfj askfksj kj s sjkjf lasjlfsj lfjljl jlk lk", "Heart asan ,nas ,fn ,masn ,mfnas ,mfn m,sanf,m nnj asn sa ,ansmfnamf ma nfmnamsdfnma,snfdman,dfmn am nfmnasmdnmsfn masnmf nsmfn mn fdm", "Swift msandmf,an ,mf nasmnf m asnm,fn asmnf kjasnfasnf,mna,mna ,fn ,fn ,mfn,mfan f,amnaf,m nfadm,fn m,fan ,mfan,adf"] var images: [String] = ["Pic1","Pic2","Pic3"] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. setupUIControls() } func setupUIControls(){ tbvData.delegate=self; tbvData.dataSource=self; } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK - UITableViewDataSource func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ return items.count; } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{ let cell = tbvData.dequeueReusableCellWithIdentifier("CustomCellId", forIndexPath: indexPath) as! CustomTVC cell.configure(text:self.items[indexPath.row], image: self.images[indexPath.row]) return cell } //MARK - UITableViewDelegate }
I have mapped the tableview to tbvData, and added the minimum uitableview delegates. The table view is filled with 3 elements contained in two arrays (items and images).
The table view cell
In the custom cell I have added an image view and a label as an example. This is the code that configures the cell:
import UIKit public class CustomTVC: UITableViewCell { @IBOutlet weak var label: UILabel! @IBOutlet weak var img: UIImageView! public func configure(text text: String, image: String) { label?.text = text img?.image = UIImage(named: image) } }
Finally
You can get also find the code here