专注收集记录技术开发学习笔记、技术难点、解决方案
网站信息搜索 >> 请输入关键词:
您当前的位置: 首页 > Swift

Swift中TableView的根本使用

发布时间:2011-06-30 07:30:25 文章来源:www.iduyao.cn 采编人员:星星草
Swift中TableView的基本使用

Xcode6新建一个项目,采用swift创建代码


创建一个ViewController继承UITableViewController

涉及了模型,控制器

模型:ZLPlace.swift

class ZLPlace: NSObject {
    var place = ""
    var visited = false
}

tableViewController 控制器

import UIKit

class ViewController: UITableViewController {
    
    // 静态数据数组,存放模型
    var arrs = [ZLPlace]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let place2 = ZLPlace()
        place2.place = "zhang2"
        arrs.append(place2)
        
        let place3 = ZLPlace()
        place3.place = "zhang3"
        arrs.append(place3)
        
        let place4 = ZLPlace()
        place4.place = "zhang1"
        arrs.append(place4)
        
        self.tableView.reloadData()
    }
    
    // 数据源方法, 返回多少组
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1;
    }
    
    // 每组有多少行
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return arrs.count;
    }
    
    // 每行展示什么内容
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell
        
        let place = arrs[indexPath.row]
        
        cell.textLabel.text = place.place
        
        return cell;
        
    }
    
    // 点击每个cell触发什么事件
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        let place = arrs[indexPath.row]
        place.visited = !place.visited;
        
        let cell = tableView.cellForRowAtIndexPath(indexPath)
        cell?.backgroundColor = UIColor.clearColor()
        if(place.visited){
            cell?.accessoryType = UITableViewCellAccessoryType.Checkmark
        }else{
            cell?.accessoryType = UITableViewCellAccessoryType.None
        }
    }
    
    // 点击编辑按钮
    @IBAction func editing(sender: AnyObject) {
        self.tableView.setEditing(true, animated: true)
    }
    
    // 删除每个cell
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == UITableViewCellEditingStyle.Delete{
            arrs.removeAtIndex(indexPath.row)
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Top)
        }
    }
    
}
<img src="http://img.blog.csdn.net/20141215234313716?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvTWV0ZXJzX0w=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />


友情提示:
信息收集于互联网,如果您发现错误或造成侵权,请及时通知本站更正或删除,具体联系方式见页面底部联系我们,谢谢。

其他相似内容:

热门推荐: