his tutorial shows how to use the cell style Custom in a Storyboard to customize the views of the cell:
- Use your TableExample project from the introductory UITableViewController tutorial or download TableExample.zip as a starting point.
- 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.
- Set FruitTableViewCell as Custom Class for the cell:
- Open the Assistant Editor and select Automatic so that you see the source code besides the selected element in the storyboard:
class FruitTableViewCell: UITableViewCell { @IBOutlet weak var label: UILabel! @IBOutlet weak var fruitImageView: UIImageView! }
- 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
}
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)
沒有留言:
張貼留言