TableView

override func viewDidLoad() {
        super.viewDidLoad()
        names = ["张三", "李四", "王五", "赵六"]
        
        //.Plain样式默认没有分隔
        let tableView = UITableView(frame: self.view.bounds, style: .Grouped)
        tableView.dataSource = self
        tableView.delegate = self
        self.view.addSubview(tableView)
        
        //Cell、Header、Footer宽度一定与TableView相同
        //x/y/width无效
        let headView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 100))
        headView.backgroundColor = UIColor.redColor()
        tableView.tableHeaderView = headView
        
        let footView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 100))
        footView.backgroundColor = UIColor.greenColor()
        tableView.tableFooterView = footView
    }
    
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 2
    }

    //询问某个section中有多少条数据
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return names!.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        //同一个Cell对象会重复使用
        //1. 在队列中获取空闲的Cell
        var cell = tableView.dequeueReusableCellWithIdentifier("cell")
        if cell == nil {
            //2. 创建可以重用的Cell对象
            cell = UITableViewCell(style: .Default, reuseIdentifier: "cell")
        }
        
        //3. 设置内容
        cell?.textLabel?.text = names![indexPath.row]
//        cell?.detailTextLabel?.text = "xxxxx"
        return cell!
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        print(indexPath.section, indexPath.row)
        print(names![indexPath.row])
    }
    

    
    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let v = UIView()
        v.backgroundColor = UIColor.cyanColor()
        return v
    }
    
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 44.0
    }

你可能感兴趣的:(TableView)