2017年3月18日 星期六

Using Custom cells to customize UITableViewCells

Ref : https://www.ralfebert.de/tutorials/ios-swift-uitableviewcontroller/custom-cells/

his tutorial shows how to use the cell style Custom in a Storyboard to customize the views of the cell:
Using Custom cells to customize table cells


  1. Use your TableExample project from the introductory UITableViewController tutorial or download TableExample.zip as a starting point.
  2. Open the storyboard and for the LabelCell in the Fruits-Controller, configure Custom as Cell Style:


3.Drag a Label and an Image View from the Object Library to the cell:



4. 

Open FruitsTableViewController.swift in the source code editor, and above the controller class, declare a class FruitTableViewCell for the cell:
import UIKit

class FruitTableViewCell: UITableViewCell {
}

class FruitsTableViewController: UITableViewController {
    // ...
}
Hint: You could also create a separate Cocoa Touch Class in a separate file. But as cells defined in a storyboard are tightly coupled to the TableViewController, defining both in the same Swift file makes sense.
  1. Set FruitTableViewCell as Custom Class for the cell:
    Custom Cell - Custom Class
  2. Open the Assistant Editor and select Automatic so that you see the source code besides the selected element in the storyboard:
  1. class FruitTableViewCell: UITableViewCell {
        @IBOutlet weak var label: UILabel!
    @IBOutlet weak var fruitImageView: UIImageView!
    }
  2. Customize the controller code in tableView(cellForRowAt:) to make use of the new cell class and its properties:
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell", for: indexPath) as! FruitTableViewCell
    
        let fruitName = fruits[indexPath.row]
    cell.label?.text = fruitName
    cell.fruitImageView?.image = UIImage(named: fruitName)
    
        return cell
    
    
  3. }
let cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell", for: indexPath) as! FruitTableViewCell

    let fruitName = fruits[indexPath.row]
cell.label?.text = fruitName
cell.fruitImageView?.image = UIImage(named: fruitName)





沒有留言:

張貼留言