Swift-UITableView的实现

来源:互联网 发布:淘宝店被关后还能重开 编辑:程序博客网 时间:2024/04/28 01:29
贴代码,于重点处做分析:

class ViewController: UIViewController,UITableViewDelegate, UITableViewDataSource{

    

    @IBOutlet var myTable : UITableView

    var items : NSMutableArray = [] //必须初始化

    

    override func viewDidLoad() {

        super.viewDidLoad()

        self.title="God"

        self.setupItems()

        self.setTableView()

        

    }

    

    func setupItems()

    {


        self.items=NSMutableArray()

        for i in 0..100

        {

            items[i]="\(i)"

        }

        

    }

    func setTableView()

    {

        myTable.delegate=self

        myTable.dataSource=self

    }

    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }

    //#prama mark - 表示图代理和数据源

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

    {

        return 100

    }

    

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

    {

        return self.items.count

    }

    

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

    {

        let cell = tableView .dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell

        

        cell.textLabel.text = "\(self.items[indexPath.row])";


        var rLabel = cell.viewWithTag(1) as UILabel

        rLabel.text = "\(items[indexPath.row])"

        //这里 就是viewWithTag的正确用法,必须和addSubview配合

        

        cell.addSubview(rLabel)

        

        

        

        return cell

    }



}


UITableView 实现可以删除的cell:

整体思路:用数组保存数据,配合一些基本的功能。

贴上主要的代码:


 @IBOutlet var myTable : UITableView

    var items = String[]()

这里是确定类型,和初始化,到后面的override func viewDidLoad() 就不用再初始化了。


func setupItems()

    {


        for i in 0..2

        {

            self.items.append("\(i)")

        }

        

    }

append是String[]数组特有的方法,注意类型配合相应的方法,找不到可以command找。


在UITableViewDelegate中,编辑如下方法:

//是否可以编辑行

    func tableView(tableView: UITableView!, canEditRowAtIndexPath indexPath: NSIndexPath!) -> Bool

    {

        return true

    }

    

    func tableView(tableView: UITableView!, editingStyleForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCellEditingStyle

    {

        // 枚举类型均可使用 .XX  这种点语法调用

        return .Delete

    }

    func tableView(tableView: UITableView!, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath!)

    {

         // 原理:删除items数组,并删除相应的cell

        self.items.removeAtIndex(indexPath.row)

        //.

        self.myTable?.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)

    }


0 0
原创粉丝点击