您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 使用技巧 >> iOS 7 技巧

Swift 用 xib 打造可複用的 UITableView 自訂 Cell

編輯:iOS 7 技巧

在 StoryBoard 裡直接設定表格單元格樣式固然方便,但當多個頁面的 tableView 需要相同外觀時,逐一設定不僅繁瑣,還容易造成程式碼冗餘。最佳解法是把單元格抽成自訂元件,實現複用。自訂 Cell 可以純程式碼實作,也能搭配 xib,本文聚焦於後者——它讓布局約束與樣式設定都變得直觀輕鬆。

一、為什麼選擇 xib

相比純程式碼,xib 在處理約束與樣式時的優勢非常明顯。本文以一個「白底圓角、左側標題、右側圖片」的單元格為示範目標,帶你看完整流程。

二、建立自訂 Cell 元件的步驟

(1)新增自訂 Cell 類別(MyTableViewCell)時,記得勾選「Also create XIB file」。

(2)建立完成後,除了自動產生的 swift 檔,還會有一個對應的 xib 檔。

(3)打開 xib,將背景設為 Clear Color,拖入一個 View 並設定約束。

小提醒:設定約束時取消勾選「Constrain to margins」,可避免系統自動加上外邊距。

(4)接著在這個 View 裡放入一個 Image View 和一個 Label(將 lines 設為 2),並補上相關約束。

(5)把 xib 中的三個元件與程式碼做關聯,並在初始化方法 awakeFromNib() 裡設定圓角。

import UIKit

class MyTableViewCell: UITableViewCell {

    @IBOutlet weak var customView: UIView!
    @IBOutlet weak var customLabel: UILabel!
    @IBOutlet weak var customImage: UIImageView!

    override func awakeFromNib() {
        super.awakeFromNib()
        // 讓 cell 呈現圓角邊框
        customView.layer.cornerRadius = 8
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
    }
}

三、使用自訂 Cell 元件

完成元件後,在 ViewController 中註冊 xib 並於 cellForRow 裡取出使用即可。關鍵在於用 registerNib 註冊,再用 dequeueReusableCellWithIdentifier 取得並轉型。

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var tableData = [["title":"Swift - 讓標籤欄按鈕 UITabBarItem 圖片居中","image":"img1.png"],
                     ["title":"Swift - 使用 SSZipArchive 實現檔案的壓縮、解壓縮","image":"img2.png"],
                     ["title":"Swift - 使用 LINQ 操作陣列/集合","image":"img3.png"],
                     ["title":"Swift - 給表格 UITableView 添加索引功能","image":"img4.png"]]

    var tableView: UITableView?

    override func viewDidLoad() {
        super.viewDidLoad()

        self.tableView = UITableView(frame: UIScreen.main.bounds, style: .plain)
        self.tableView!.delegate = self
        self.tableView!.dataSource = self
        self.tableView!.backgroundColor = UIColor(red: 0xf0/255, green: 0xf0/255, blue: 0xf0/255, alpha: 1)
        self.tableView!.separatorStyle = .none

        // 註冊 xib 方便複用
        self.tableView!.registerNib(UINib(nibName: "MyTableViewCell", bundle: nil),
                                    forCellReuseIdentifier: "myCell")

        self.view.addSubview(self.tableView!)
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.tableData.count
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "myCell") as! MyTableViewCell
        let item = tableData[indexPath.row]
        cell.customLabel.text = item["title"]
        cell.customImage.image = UIImage(named: item["image"]!)
        return cell
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

透過 xib 建立自訂 Cell,不僅讓樣式調整一目了然,也靠著 reuse identifier 實現了 Cell 複用,是提升表格效能與開發效率 both 兼顧的實用技巧。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved