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

swift总结1

2015-09-01 12:31 447 查看
一 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;

     }()
 (3)申明一个tableview的变量 
var aTableView:UITableView!  
说明只是 申明,不用初始化  用 !(解包)或者 ?(可能为空)

(4)实现代理方法 

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

}
(5)在viewDidLoad方法中初始化
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: