最近学习了一下swift,学完了基本语法尝试写了一个tableView,确实遇到好多坑,下面上代码,和大家交流交流
怎么创建一个程序就不说了。
import UIKit
Tips:Swift里面的协议继承直接这样写就好了
class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate{
let Screen_W = UIScreen.mainScreen().bounds.size.width
let Screen_H = UIScreen.mainScreen().bounds.size.height
Tips:这里相当于创建类的私有属性,我试了一下,如果不加private修饰的话,外部是可以访问的
private var tableView:UITableView!
private let _headerViewHeight:CGFloat = 250.0
// MARK:--- LIFE CYCLE
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.setTableView()
self.setTableHeader()
}
// MARK:--- UI
// MARK:--- SET TABLE
private func setTableView(){
tableView = UITableView()
tableView.frame = CGRectMake(0, 20.0, Screen_W ,Screen_H - 20.0)
tableView.delegate = self
tableView.dataSource = self
self.view.addSubview(tableView!)
Tips:这里是注册一个cell类,我试着用以前传统的方式创建cell,会崩溃,不知道为啥,所以都这么干
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
}
// MARK:--- SET TABLE HEADER
private func setTableHeader(){
let headerView = UIView()
headerView.frame = CGRectMake(0, 0, Screen_W, _headerViewHeight)
headerView.backgroundColor = UIColor.orangeColor()
let headerImageView = UIImageView(frame: headerView.bounds)
headerImageView.image = UIImage(named: "headerImahe.jpg")
headerView.addSubview(headerImageView)
headerImageView.backgroundColor = UIColor.blackColor()
tableView.tableHeaderView = headerView
}
// MARK:--- UITableViewDelegate
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return 10
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
Tips:如果自己封装的cell的话,这里要这么写:
tableView.dequeueReusableCellWithIdentifier(
"OwnerInfoCell", forIndexPath: indexPath) as! OwnerInfoCell
let cell = tableView.dequeueReusableCellWithIdentifier(
"cell", forIndexPath: indexPath)
cell.selectionStyle = UITableViewCellSelectionStyle.None
cell.textLabel?.text = "This Row is : " + String(indexPath.row)
return cell
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return _headerViewHieght
}
}