Swift Custom Table View Cell Example 自定义 UITableViewCell


Custom Table View Cell Example

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.blueColor(), UIColor.yellowColor(), UIColor.magentaColor(), UIColor.redColor(), UIColor.brownColor()]      // 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, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {          let cell:MyCustomCell = self.tableView.dequeueReusableCellWithIdentifier(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, didSelectRowAtIndexPath indexPath: NSIndexPath) {         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 pull the bottom of the prototype cell down so that it is a little bigger.) 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 100×100.

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.


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


  • 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.

How do I set adaptive multiline UILabel text? UILable 文本自动换行

 This is much better approach if you are looking for multiline dynamic text label which exactly takes the space based on its text.

No sizeToFit, preferredMaxLayoutWidth used

Below is how it will work.

enter image description here

 Lets set up the project. Take a Single View application and in Storyboard Add a UILabel and a UIButton. Define constraints to UILabel as below snapshot:

enter image description here

Set the Label properties as below image:

enter image description here

Add the constraints to the UIButton. Make sure that vertical spacing of 100 is between UILabel and UIButton

enter image description here

Now set the priority of the trailing constraint of UILabel as 749

enter image description here

Now set the Horizontal Content Hugging and Horizontal Content Compression properties of UILabel as 750 and 748

enter image description here

Below is my controller class. You have to connect UILabel property and Button action from storyboard to viewcontroller class.

import UIKit  class ViewController: UIViewController {  @IBOutlet weak var textLabel: UILabel! var count = 0 let items = ["jackson is not any more in this world", "Jonny jonny yes papa eating sugar no papa", "Ab", "What you do is what will happen to you despite of all measures taken to reverse the phenonmenon of the nature"]   @IBAction func updateLabelText(sender: UIButton) {     if count > 3 {         count = 0     }     textLabel.text = items[count]     count = count + 1 }  override func viewDidLoad() {     super.viewDidLoad()     // Do any additional setup after loading the view, typically from a nib.     //self.textLabel.sizeToFit()     //self.textLabel.preferredMaxLayoutWidth = 500 }  override func didReceiveMemoryWarning() {     super.didReceiveMemoryWarning()     // Dispose of any resources that can be recreated. }   }

Thats it. This will automatically resize the UILabel based on its content and also you can see the UIButton is also adjusted accordingly.