Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating custom tableview cells in swift

I have a custom cell class with a couple of IBOutlets. I have added the class to the storyboard. I have connected all my outlets. my cellForRowAtIndexPath function looks like this:

override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {         let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as SwipeableCell          cell.mainTextLabel.text = self.venueService.mainCategoriesArray()[indexPath.row]          return cell     } 

Here is my custom cell class:

class SwipeableCell: UITableViewCell {     @IBOutlet var option1: UIButton     @IBOutlet var option2: UIButton     @IBOutlet var topLayerView : UIView     @IBOutlet var mainTextLabel : UILabel     @IBOutlet var categoryIcon : UIImageView      init(style: UITableViewCellStyle, reuseIdentifier: String!) {         super.init(style: style, reuseIdentifier: reuseIdentifier)       } } 

When I run the app, all my cell are empty. I have logged out self.venueService.mainCategoriesArray() and it contains all the correct strings. I have also tried putting an actual string equal to the label, and that produces the same result.

What am I missing? Any help is appreciated.

like image 457
Nilzone- Avatar asked Jun 11 '14 19:06

Nilzone-


People also ask

Can we use Tableview in SwiftUI?

In this blog post, I'll introduce the collection view Table in SwiftUI and explain how to leverage this view on iOS 16 to build a multiplatform app. SwiftUI provides several collection views that you can use to assemble other views into dynamic groupings with complex, built-in behaviors.

How do I change the Tableview style in Swift?

You can't change the tableview style dinamically, you have to do it in your xib file or storyboard if you have one. If you don't use a storyboard or a xib, and prefer to create the tableview programmatically, specify the style while creating the tableview using the - initWithFrame:style: method.

What is Tableview in Swift?

Overview. Table views in iOS display rows of vertically scrolling content in a single column. Each row in the table contains one piece of your app's content. For example, the Contacts app displays the name of each contact in a separate row, and the main page of the Settings app displays the available groups of settings ...


1 Answers

Custom Table View Cell Example

Tested with Xcode 9 (edit also tested on 11 / 12 Beta 2) and Swift 4 (edit: also tested on 5.2)

The asker of the original question has solved their problem. I am adding this answer as a mini self contained example project for others who are trying to do the same thing.

The finished project should look like this:

enter image description here

Create a new project

It can be just a Single View Application.

Add the code

Add a new Swift file to your project. Name it MyCustomCell.swift. This class will hold the outlets for the views that you add to your cell in the storyboard.

import UIKit class MyCustomCell: UITableViewCell {     @IBOutlet weak var myView: UIView!     @IBOutlet weak var myCellLabel: UILabel! } 

We will connect these outlets later.

Open ViewController.swift and make sure you have the following content:

import UIKit class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {          // These strings will be the data for the table view cells     let animals: [String] = ["Horse", "Cow", "Camel", "Sheep", "Goat"]          // These are the colors of the square views in our table view cells.     // In a real project you might use UIImages.     let colors = [UIColor.blue, UIColor.yellow, UIColor.magenta, UIColor.red, UIColor.brown]          // Don't forget to enter this in IB also     let cellReuseIdentifier = "cell"          @IBOutlet var tableView: UITableView!          override func viewDidLoad() {         super.viewDidLoad()                  tableView.delegate = self         tableView.dataSource = self     }          // number of rows in table view     func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {         return self.animals.count     }          // create a cell for each table view row     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {                  let cell:MyCustomCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as! MyCustomCell                  cell.myView.backgroundColor = self.colors[indexPath.row]         cell.myCellLabel.text = self.animals[indexPath.row]                  return cell     }          // method to run when table view cell is tapped     func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {         print("You tapped cell number \(indexPath.row).")     } } 

Setup the storyboard

Add a Table View to your view controller and use auto layout to pin it to the four sides of the View Controller. Then drag a Table View Cell onto the Table View. And then drag a View and a Label onto the Prototype cell. (You may need to select the Table View Cell and manually set the Row Height to something taller in the Size inspector so that you have more room to work with.) Use auto layout to fix the View and the Label how you want them arranged within the content view of the Table View Cell. For example, I made my View be 100x100.

enter image description here

Other IB settings

Custom class name and Identifier

Select the Table View Cell and set the custom class to be MyCustomCell (the name of the class in the Swift file we added). Also set the Identifier to be cell (the same string that we used for the cellReuseIdentifier in the code above.

enter image description here

Hook Up the Outlets

  • Control drag from the Table View in the storyboard to the tableView variable in the ViewController code.
  • Do the same for the View and the Label in your Prototype cell to the myView and myCellLabel variables in the MyCustomCell class.

Finished

That's it. You should be able to run your project now.

Notes

  • The colored views that I used here could be replaced with anything. An obvious example would be a UIImageView.
  • If you are just trying to get a TableView to work, see this even more basic example.
  • If you need a Table View with variable cell heights, see this example.
like image 165
Suragch Avatar answered Oct 01 '22 02:10

Suragch