Swift使用xib製作UITableView的自訂Cell(自訂儲存格的複用)

來源:互聯網
上載者:User

在StoryBoard中,我們可以很方便地設定表格(tableView)內部儲存格(cell)樣式。但如果多個頁面的tableView儲存格樣式都一樣的話,再一個個單獨設定不僅麻煩,而且會造成代碼冗餘。

最好的辦法就是把儲存格提取出來做成自訂群組件,從而實現cell的複用。
對於自訂儲存格組件,我門既可以通過繼承 UITableViewCell,使用純程式碼來實現。也可以配合 XIB 來實現。前面一種方法我原來寫過很多範例了,本文介紹後面一種方法。

1,使用xib製作tableView的cell介紹

同純程式碼相比,xib實現自訂樣式會方便很多。不管布局約束,還是樣式的設定,使用xib都很簡單。
下面通過xib實現如下的自訂儲存格:白底圓角,左側是標題文本,右側是圖片。

             
 
2,自訂cell組件的步驟
(1)首先,建立自訂cell類(MyTableViewCell)的時候選中“Also create XIB file”
(2)建立完畢後,我們可以看到除了自動產生了一個 swift 檔案,還有個對應的 xib 檔案
(3)開啟xib檔案,將其背景色設為Clear Color。向裡面拖入一個 View 組件,並設定約束。

注意:設定約束時去掉“Constrain to margins”的勾選,這樣做防止自動添加外邊距。

                    
  
(4)接著往新增的View組件裡面拖入一個 Image View 組件和一個 Lable 組件(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)
    }  
}

3,自訂cell組件的使用

 代碼如下 複製代碼


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"],
    ["title":"Swift - 清單項目尾部附件點擊響應","image":"img5.png"],
    ["title":"Swift - 自由調整表徵圖按鈕中的表徵圖和文字位置","image":"img6.png"]]
    
    var tableView:UITableView?
    
    override func loadView() {
        super.loadView()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //建立表視圖
        self.tableView = UITableView(frame: UIScreen.mainScreen().applicationFrame,
            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
        
        //建立一個重用的儲存格
        self.tableView!.registerNib(UINib(nibName:"MyTableViewCell", bundle:nil),
            forCellReuseIdentifier:"myCell")
        
        self.view.addSubview(self.tableView!)
    }
    
    //在本例中,只有一個分區
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1;
    }
    
    //返回表格行數(也就是返回控制項數)
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.tableData.count
    }
    
    //儲存格高度
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath)
        -> CGFloat {
        return 100
    }
    
    //建立各單元顯示內容(建立參數indexPath指定的單元)
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath)
        -> UITableViewCell
    {
        let cell:MyTableViewCell = tableView.dequeueReusableCellWithIdentifier("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()
    }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.