利用swift写的tableView

最近在学习用swift写东西,这里用swift写的一个关于tableView的一个小实例,希望可以帮到和我一样在学习swift道路上不断爬坑,勇往直前的小伙伴们。文章里面加的详细的注释说明,同时欢迎朋友在评论里面提意见,我会继续努力的。

下面是代码部分:

    //建立tableView
    var tableView = UITableView()
    let cellID = "cellID"

    //var tableData = (titles:[String], values:[String])?

//建立数据数组

    var tableData = ["宝宝0","宝宝1","宝宝2","宝宝3","宝宝4","宝宝5","宝宝6","宝宝7","宝宝8","宝宝9","宝宝10","宝宝11","宝宝12","宝宝13","宝宝14","宝宝15","宝宝16","宝宝17","宝宝18","宝宝19","宝宝20","宝宝21","宝宝22","宝宝23","宝宝24","宝宝25","宝宝26","宝宝27","宝宝28","宝宝29","宝宝30","宝宝31"]

    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        self.title = "tableView"
        self.view.backgroundColor = UIColor.blueColor()
        //设置tableView的frame
        self.tableView.frame = CGRectMake(0, 0, self.view.frame.width, self.view.frame.height)

       

        //当需要加载单独cell类的时候需要将cell注册之后才能加载到工程里面去

        //let nib = UINib(nibName: "CellList",bundle: nil)//cell文件名

        //self.tableView.registerNib(nib, forCellReuseIdentifier: cellID)

//tableView的两个代理方法

        self.tableView.delegate = self
        self.tableView.dataSource = self
        
        self.view.addSubview(self.tableView)
        //刷新表

        self.showData()

    }

   //刷新表

func showData() {

        
        self.tableView.reloadData()
    }

  //内存警告时调用

  override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()
    }
}

//talbeView 的两个代理方法的实现,其实这两个代理还能加到class声明的后面,代理方法的时候和OC里面的实现是一样的

extension TestViewController:UITableViewDataSource {

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return tableData.count
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
//        let cell:SwiftCell = tableView.dequeueReusableCellWithIdentifier("SwiftCell")
//            as! SwiftCell
//        let item = tableData[indexPath.row]
//        cell.customLabel.text = item
//        //cell.customImage.image = UIImage(named:item["image"]!)
//        return cell
        
        let cell = UITableViewCell(style: UITableViewCellStyle.Subtitle,reuseIdentifier: cellID)
        
        cell.textLabel?.text = tableData[indexPath.row]
        return cell
    }
}

extension TestViewController:UITableViewDelegate{
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
    
        print(tableData[indexPath.row])
    }
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
    {
        return 50
    }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值