swift 中三種創建UITableView的方法和之間的區別

·UITableView其它一些東西在這里不多講,這里的就是講解UITableView的創建。

UITableView的創建有三種方法分別是純代碼、XIB、storyboard。下面就是創建的代碼

1.純代碼的創建

首先實例化UITableView(我所有的創建都是在UIViewController類中完成的)

lettableView =UITableView(frame:UIScreen.mainScreen().bounds, style:UITableViewStyle.Plain)

tableView.delegate=self

tableView.dataSource=self

self.view.addSubview(tableView)

必要的幾個代理方法

func numberOfSectionsInTableView(tableView:UITableView) ->Int{

return1

}

func tableView(tableView:UITableView, numberOfRowsInSection section:Int) ->Int{

return3

}

這一塊是自定義cell

func tableView(tableView:UITableView, cellForRowAtIndexPath indexPath:NSIndexPath) ->UITableViewCell{

letcell=TYCodeTableViewCell.codeTableViewCell(tableView)as!TYCodeTableViewCell

returncell

}

下面是具體用純代碼創建cell

class TYCodeTableViewCell:UITableViewCell{

class func codeTableViewCell(tableView :UITableView) ->AnyObject{

let ID ="cell"http://設置標記

var cell = tableView.dequeueReusableCellWithIdentifier(ID)//從緩存中提取

if cell ==nil {//沒有就創建cell

cell =TYCodeTableViewCell(style:UITableViewCellStyle.Default, reuseIdentifier: ID)

//在這里創建cell中的其它控件,是會出現亂序,你的邏輯最好不要在這里實現

}

return cell!//返回cell

}

override func awakeFromNib() {

super.awakeFromNib()

// Initialization code

}

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

super.setSelected(selected, animated: animated)

// Configure the view for the selected state

}

}

以上就是純代碼的創建

XIB的創建

因為我們使用XIB所以它的創建與有點不一樣

lettableView =UITableView(frame:UIScreen.mainScreen().bounds, style:UITableViewStyle.Plain)

tableView.delegate=self

tableView.dataSource=self

self.view.addSubview(tableView)

//這里是注冊XIB類似純代碼中的創建cell

letnib =UINib(nibName:"TYXIBTableViewCell", bundle:nil)

tableView.registerNib(nib, forCellReuseIdentifier:id)

因為上面已經創建所以下面我只要到緩存中提取就可以了,這里也是自定義cell 為TYXIBTableViewCell

func tableView(tableView:UITableView, cellForRowAtIndexPath indexPath:NSIndexPath) ->UITableViewCell{

let cell :TYXIBTableViewCell= (tableView.dequeueReusableCellWithIdentifier(id, forIndexPath: indexPath)) as!TYXIBTableViewCell

returncell

}

使用storyboard創建就更加簡單了


在這里創建了TableView和cell代碼中只要從緩存中提取就可以了

func tableView(tableView:UITableView, cellForRowAtIndexPath indexPath:NSIndexPath) ->UITableViewCell{

letcell :TYStoryboardTableViewCell= tableView.dequeueReusableCellWithIdentifier("TYStoryboardTableViewCell", forIndexPath: indexPath) as! TYStoryboardTableViewCell

returncell

}

上面就是從緩存中提取cell

下面是具體的代碼

https://github.com/tangyi1234/CellTypeTableView.git

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容