iOS使用Swift创建UITableView

来源:互联网 发布:思讯收银软件多少钱 编辑:程序博客网 时间:2024/04/29 17:24

WWDC 2014上,苹果公布了全新的编程语言Swift,这两天利用业余时间大概研究了一下,感觉Swift挺不错的。用Swift创建的文件不再有.h和.m之分,而是统一采用swift作为后缀。swift代码跟OC不能写在一个文件中,需要分成两个文件来写。使用OC创建文件后,会自动生成一个Hello-Bridging-Header.h头文件,把OC写的.h文件import到这个Bridging文件中即可。

闲来无事,用Swift初始化了一个UITableView,拿出来跟各位看官分享一下Swift的语法。具体实现代码如下:

import UIKit// 跟OC一样,这个位置需要引入代理class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {        override func viewDidLoad() {        super.viewDidLoad()        // Do any additional setup after loading the view, typically from a nib.        // 初始化tablview        var tableView: UITableView = UITableView(frame: CGRect(x: 0, y: 20, width: self.view.frame.size.width, height: self.view.frame.size.height), style: UITableViewStyle.Plain)        // 设置背景色        tableView.backgroundColor = UIColor.orangeColor()        // 设置代理        tableView.delegate = self        tableView.dataSource = self        self.view.addSubview(tableView)    }    override func didReceiveMemoryWarning() {        super.didReceiveMemoryWarning()        // Dispose of any resources that can be recreated.    }    // #pragma mark - UITableViewDataSource    func numberOfSectionsInTableView(tableView: UITableView!) -> Int {        return 1    }        func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {        return 20    }        func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!  {        let cell = UITableViewCell(style: .Subtitle, reuseIdentifier: nil)        cell.textLabel.text = "\(indexPath.row)"        return cell    }}

0 0
原创粉丝点击