前幾篇是透過StoryBoard來建立客製的cell view
這篇則是要寫如何透過xib來完成cell view
一樣先建立一個對應的Class ```swift
import Uikit
public class XibCell : UITableViewCell{
@IBOutlet weak var lblTitle: UILabel! //title的label
@IBOutlet weak var imgIcon: UIImageView! //icon的小圖片
public override init(){
super.init();
}
public required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder);
}
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| * 建立一個.xib的View [![](http://3.bp.blogspot.com/-i547UQ5vRNc/VPQbuDo0_LI/AAAAAAAAEXo/zna_SQsYioA/s1600/%E8%9E%A2%E5%B9%95%E5%BF%AB%E7%85%A7%2B2015-03-02%2B%E4%B8%8B%E5%8D%884.12.47.png)](http://3.bp.blogspot.com/-i547UQ5vRNc/VPQbuDo0_LI/AAAAAAAAEXo/zna_SQsYioA/s1600/%E8%9E%A2%E5%B9%95%E5%BF%AB%E7%85%A7%2B2015-03-02%2B%E4%B8%8B%E5%8D%884.12.47.png) * 指定xib的class為XibCell [![](http://3.bp.blogspot.com/-CkRdJKdxYcs/VPQcWDhQ8rI/AAAAAAAAEXw/e334Wa4ZKFc/s1600/%E8%9E%A2%E5%B9%95%E5%BF%AB%E7%85%A7%2B2015-03-02%2B%E4%B8%8B%E5%8D%884.14.39.png)](http://3.bp.blogspot.com/-CkRdJKdxYcs/VPQcWDhQ8rI/AAAAAAAAEXw/e334Wa4ZKFc/s1600/%E8%9E%A2%E5%B9%95%E5%BF%AB%E7%85%A7%2B2015-03-02%2B%E4%B8%8B%E5%8D%884.14.39.png) * 把UI的關聯拉起來 [![](http://2.bp.blogspot.com/-qDluWRV2fRc/VPQeGTJOPfI/AAAAAAAAEX8/Cna7u8bnTWc/s1600/%E8%9E%A2%E5%B9%95%E5%BF%AB%E7%85%A7%2B2015-03-02%2B%E4%B8%8B%E5%8D%884.23.35.png)](http://2.bp.blogspot.com/-qDluWRV2fRc/VPQeGTJOPfI/AAAAAAAAEX8/Cna7u8bnTWc/s1600/%E8%9E%A2%E5%B9%95%E5%BF%AB%E7%85%A7%2B2015-03-02%2B%E4%B8%8B%E5%8D%884.23.35.png) * controller的寫法大同小異,但請注意cellForRowAtIndexPath的寫法改變 ```swift import UIKit class xibTableViewController: UIViewController ,UITableViewDelegate , UITableViewDataSource{ @IBOutlet weak var uitable: UITableView! var data :[String]!; //資料來源 override func viewDidLoad() { super.viewDidLoad(); data = []; data.append("籃球"); data.append("棒球"); data.append("足球"); uitable.delegate = self; uitable.dataSource = self; } //這個table包含幾個section func numberOfSectionsInTableView(tableView: UITableView!) -> Int { return 1 } //每個section有幾個row func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return data.count; } //每個row顯示的內容 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let identifier = "cellid"; var cell : XibCell? = self.uitable.dequeueReusableCellWithIdentifier(identifier) as? XibCell; if cell == nil{ //載入xib當作cell view uitable.registerNib(UINib(nibName: "xibcell", bundle: nil), forCellReuseIdentifier: identifier); cell = self.uitable.dequeueReusableCellWithIdentifier(identifier) as? XibCell; } //indexPath.row 可以知道目前是要製作第幾列的view cell?.lblTitle?.text = data[indexPath.row]; cell?.imgIcon.image = UIImage(named: "icon-factory"); return cell!; } }
|
最後呈現結果