UITableView 是iOS中很常用的一个控件,下面我们就来实现一下Swift中有关UITableView的创建和使用方法
首先,新建一个项目起名TestTableViewSwift 默认语言选择Swift
接下来我们在默认生成的ViewController.swift 中创建UITableView
首先定义变量
var _tableView:UITableView!
创建 并添加到当前View上
_tableView=UITableView(frame: CGRectMake(0,100,self.view.bounds.size.width,self.view.bounds.size.height),style:UITableViewStyle.Plain) self.view.addSubview(_tableView)
我们运行会发现一张空表出现了
接下来我们给table中添加数据
首先我们准备一个数组
var _dataArray:[String]!
//准备数据 _dataArray=[String]() for i in 1...10 { _dataArray.append("第\(i)行") }
给ViewController添加一个协议
class ViewController: UIViewController,UITableViewDataSource {
将刚才准备的数组添加到tableView上
_tableView.dataSource=self
实现两个协议方法
//设置每一行的内容 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 }
再执行看效果
基本实现了数据展示
源码名称:TestTableViewSwift1.zip
下节我们来丰富一下每行所展示的内容
下节地址 :http://www.jb51.cc/article/p-sybrqxqe-bbq.html
苹果开发群2 :492222303 欢迎加入 欢迎讨论问题
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。