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"//设置标记

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创建就更加简单了


swift 中三种创建UITableView的方法和之间的区别_第1张图片

在这里创建了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

你可能感兴趣的:(swift 中三种创建UITableView的方法和之间的区别)