一 tableview的使用
1/ 创建一个数据模型的类 供网络请求数据
class ZYFruit:NSObject {
var name: String =String ()
var desc: String =String ()
var fruit: NSArray = NSArray ()
}
2/ 在视图控制器中添加 tableview(1)首先要继承 代理
class ViewController:UIViewController, UITableViewDataSource,UITableViewDelegate
(2) 在类中 初始化数据
var dataList: NSArray = {
var zyFriut1: ZYFruit = ZYFruit()
zyFriut1.name = "第一筐水果"
zyFriut1.desc = "多汁"
var list:NSMutableArray = NSMutableArray ()
for var index:Int = 0; index <10 ; ++index{
list .addObject("\(zyFriut1.name) - " +"\(index)")
}
zyFriut1.fruit = list
var zyFriut2: ZYFruit = ZYFruit()
zyFriut2.name = "第二筐水果"
zyFriut2.desc = "好吃"
var list2:NSMutableArray = NSMutableArray ()
for var index:Int = 0; index <20 ; ++index{
list2 .addObject("\(zyFriut2.name) - " +"\(index)")
}
zyFriut2.fruit = list2
var tempList: NSArray = [zyFriut1, zyFriut2]
return tempList;
}()
var aTableView:UITableView!
说明只是 申明,不用初始化 用 !(解包)或者 ?(可能为空)
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return dataList.count;
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) ->Int{
return dataList[section].fruit.count;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:UITableViewCell = UITableViewCell (style: .Default, reuseIdentifier:nil)
let zyFruit:ZYFruit = dataList[indexPath.section] as!ZYFruit
cell.textLabel?.text = zyFruit.fruit[indexPath.row]as? String
return cell
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return dataList[section].name
}
func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? {
return dataList[section].desc
}