Swfit 學習tableview

class OnrViewController:UIViewController,UITableViewDelegate,UITableViewDataSource{

    //創建tableview

    var  tableView : UITableView?

    let URL :String = "http://piao.163.com/m/movie/list.html?type=0&city=110000&apiVer=14&mobileType=android&deviceId=r4a5ba63afbabd7a70ceeaf8485f7942e&channel=wandoujia&ver=4.9"

    //創建一個數組

    var dataSource:NSArray = NSArray()

    

    override func viewDidLoad() {

        super.viewDidLoad()

        // Do any additional setup after loading the view.

      

    }

    

    override func viewDidAppear(animated: Bool) {

        super.viewDidAppear(animated)

        //創建UI

        creatUI()

        //創建 數據源

        createDataSource()

    }

    

    func creatUI() {

        tableView = UITableView(frame: self.view.bounds,style: .Plain)

        tableView!.delegate = self

        tableView!.dataSource = self

        tableView!.separatorStyle = .SingleLineEtched

        

        self.view.addSubview(tableView!)

    }

    

    func createDataSource (){

        let url:NSURL = NSURL(string: URL)!

        let request : NSURLRequest = NSURLRequest(URL:url)

        NSURLConnection.sendAsynchronousRequest(request, queue:NSOperationQueue.mainQueue()) { (response, data, error) in

            let json :AnyObject =try!NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)

            self.dataSource = json.objectForKey("list"as!NSArray

            self.tableView!.reloadData()

        }

        

    }

    

    //代理方法

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

        return self.dataSource.count;

    }

    

    //代理方法 獲取cell

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

        let identifer = "tableviewcell"

        var cell = tableView.dequeueReusableCellWithIdentifier(identifer)

        if (cell == nil) {

            cell = UITableViewCell(style:.Default,reuseIdentifier: identifer)

            cell!.selectionStyle = .None

        }

//        cell!.text Label!.text = "tableviewcell"

        let obj:NSDictionary = self.dataSource[indexPath.rowas!NSDictionary

        let name:String = obj.objectForKey("name")as!String

        

       cell!.textLabel!.text = name

        cell!.backgroundColor = UIColor.blueColor()

       return cell!

    }

    

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath:NSIndexPath) {

        if (indexPath.row == 0) {

            print("sdadadadad")

        }

    }

    

    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath:NSIndexPath) -> CGFloat {

        return 200

    }

    



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章