您的位置:首页 > 移动开发 > Swift

swift UITableView(一)

2015-11-09 13:52 501 查看
UITableView 是iOS中很常用的一个控件,下面我们就来实现一下Swift中有关UITableView的创建和使用方法

首先,新建一个项目起名TestTableViewSwift  默认语言选择Swift





接下来我们在默认生成的ViewController.swift 中创建UITableView

首先定义变量

[objc] view
plaincopy

var _tableView:UITableView!  

创建 并添加到当前View上

[objc] view
plaincopy

_tableView=UITableView(frame: CGRectMake(0, 100, self.view.bounds.size.width, self.view.bounds.size.height),style:UITableViewStyle.Plain)  

self.view.addSubview(_tableView)  

我们运行会发现一张空表出现了



接下来我们给table中添加数据

首先我们准备一个数组

[html] view
plaincopy

var _dataArray:[String]!  

[html] view
plaincopy

//准备数据  

_dataArray=[String]()  

for i in 1...10  

{  

    _dataArray.append("第\(i)行")  

}  

给ViewController添加一个协议

[html] view
plaincopy

class ViewController: UIViewController,UITableViewDataSource {  

将刚才准备的数组添加到tableView上

[html] view
plaincopy

_tableView.dataSource=self  

实现两个协议方法

[html] view
plaincopy

//设置每一行的内容  

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

    var cellid="cellid"  

      

    var cell=tableView.dequeueReusableCellWithIdentifier(cellid) as? UITableViewCell  

      

    if cell==nil  

    {  

        cell=UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: cellid)  

          

    }  

    cell!.textLabel?.text=_dataArray![indexPath.row]  

    return cell!  

}  

  

//设置需要展示的行数  

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

    return _dataArray.count  

}  

再执行看效果



基本实现了数据展示
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: