UITableView
平常我們用的最多的列表展示應(yīng)該就是
UITableView
,UITableView
繼承自UIScrollView
,因此支持垂直滾動(dòng),而且性能極佳,加上本身的一些方法足夠讓我們運(yùn)用到許多地方莺琳。
1、基本用法
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{
var testArray = ["one","two","three","four"]
override func viewDidLoad() {
super.viewDidLoad()
self .makeTestTableView()
}
private lazy var tableView: UITableView = {
let testTableView = UITableView()
testTableView.delegate = self
testTableView.dataSource = self
// 木有后半部分分割線的顯示
testTableView.tableFooterView = UIView()
// 注冊(cè)
testTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "testCellIden")
return testTableView
}()
func makeTestTableView(){
/* 備注下载慈,之前是2.1之前是建議不用self的惭等,但是最近2.1又提出加self這個(gè)提案
https://github.com/apple/swift-evolution/blob/master/proposals/0009-require-self-for-accessing-instance-members.md
目前還是看個(gè)人習(xí)慣吧
*/
self.tableView.frame = self.view.frame
self.view .addSubview(self.tableView)
}
//MARK: UITableView--Delegate
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.testArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView .dequeueReusableCellWithIdentifier("testCellIden")
cell?.textLabel?.text = "there is \(self.testArray[indexPath.row])"
return cell!
}
}
2、自定義的情況
注意registerClass
和dequeueReusableCellWithIdentifier
兩個(gè)方法的不同就OK了
testTableView.registerClass(TestTableViewCell.self, forCellReuseIdentifier: "testCellIden")
let cell = tableView .dequeueReusableCellWithIdentifier("testCellIden") as! TestTableViewCell
假如是XIB
//nibName指的是我們創(chuàng)建的Cell文件名
let nib = UINib(nibName: "testListCell", bundle: nil)
self.tableView.registerNib(nib, forCellReuseIdentifier: "iden")
3办铡、要注意的地方
3-1辞做、其他可能用到的代理方法
func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
// 選中的情況
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
// 刪除 或者 說編輯
let index=indexPath.row
self.testArray.removeAtIndex(index)
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Bottom)
}
3-2琳要、當(dāng)Cell 高度不定的時(shí)候
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
// public func boundingRectWithSize(size: CGSize, options: NSStringDrawingOptions, attributes: [String : AnyObject]?, context: NSStringDrawingContext?) -> CGRect
return
}
UITableView需要用的太多了,繼續(xù)學(xué)習(xí)中···