美文网首页
swift之tableView

swift之tableView

作者: HJXu | 来源:发表于2016-07-13 15:48 被阅读93次

抽空继续研究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)
    }
}

相关文章

网友评论

      本文标题:swift之tableView

      本文链接:https://www.haomeiwen.com/subject/xhasjttx.html