【swift學習筆記】三.使用xib自定義UITableViewCell

使用xib自定義tableviewCell看一下效果圖ide

1.自定義列學習

新建一個xib文件 carTblCell,拖放一個UITableViewCell,再拖放一個圖片和一個文本框到tableviewcell上ui

並給咱們的xib一個標識spa

爲了學習,我這裏的xib和後臺的class是分開建的。咱們再建一個cocoa touch class文件名稱爲CarCellTableViewCell繼承自UITableViewCell3d

並把咱們的xib和新建的CarCellTableViewCell創建聯接code

 

在CarCellTableViewCell裏創建和xib的圖片和文本框的輸出blog

import UIKit

class CarCellTableViewCell: UITableViewCell {

    @IBOutlet weak var cellImg: UIImageView!

    @IBOutlet weak var lbCell: UILabel!
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
        cellImg.layer.borderWidth = 1
        cellImg.layer.masksToBounds = true
        //cellImg.layer.cornerRadius = 31
    }

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

        // Configure the view for the selected state
    }

}

 

2.關聯cell和tableview繼承

1. 在main.storyboard上拖放一個uitableview,並在後臺代碼創建輸出聯接事件

1.在load事件裏註冊xib圖片

2.在tableveiw的方法裏獲得當前的列,指定數據源。

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet var tableView: UITableView!
    var tableData: [String] = ["BMW", "Ferrari", "Lambo"]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let cellNib = UINib(nibName: "carTblCell", bundle: nil)
        tableView.registerNib(cellNib, forCellReuseIdentifier: "cell")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
         return tableData.count
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell: CarCellTableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as! CarCellTableViewCell
        cell.lbCell.text = tableData[indexPath.row]
        cell.cellImg.image = UIImage(named: tableData[indexPath.row])
        
        return cell
    }
    
    func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
        print("\(indexPath.row)")
    }
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 70
    }
}

 源碼:CustomerTableCellDemo.zip

相關文章
相關標籤/搜索