swift之tableView

抽空继续研究swift,本文简单介绍用swift创建tableView,大神请无视😄
代码如下

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 添加tableView的控件
        let tableView = UITableView()
        tableView.frame = self.view.bounds
        self.view.addSubview(tableView)
        
        // 设置数据源,设置数据
        tableView.dataSource = self
        tableView.delegate = self
    }

}

// 遵守协议的方式,直接在继承的父类后跟,+协议即可
// 相当于OC中的category
extension ViewController : UITableViewDataSource
{
    // MARK:- 实现数据源方法
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 100
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let ID : String = "CELL"
        var cell = tableView.dequeueReusableCellWithIdentifier(ID)
        
        if cell == nil {
            cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: ID)
        }
        
        cell?.textLabel?.text = "swift:\(indexPath.row)"
        
        return cell!
    }
}

extension ViewController : UITableViewDelegate
{
    // MARK:- 实现代理方法
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        print(indexPath.row)
    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容