類UITableView表示一個列表視圖,此視圖能夠顯示列表,而且列表能夠分爲多個區間(section)。javascript
假設一個案例:java
顯示計算機語言清單(["java","swift","js"]和操做系統的清單 ["Windows","OS X","Linux"]程序員
這個清單在一個UITableView上作分區顯示,分爲兩個區間swift
那麼代碼以下:數組
import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { self.window = UIWindow(frame: UIScreen.main.bounds) let page = Page() page.view.backgroundColor = .blue self.window!.rootViewController = page self.window?.makeKeyAndVisible() return true } } class Page: UIViewController { var a : Table! override func viewDidLoad() { super.viewDidLoad() a = Table() a.frame = CGRect(x: 0,y: 50,width: 300,height: 500) self.view.addSubview(a) } } class Table : UITableView,UITableViewDataSource,UITableViewDelegate{ let sect = ["Lang","OS"] let lang = ["java","swift","js"] let os = ["Windows","OS X","Linux"] override init(frame: CGRect, style: UITableViewStyle) { super.init(frame:frame,style:style) self.dataSource = self self.delegate = self } required init?(coder aDecoder: NSCoder) { super.init(coder:aDecoder) } func numberOfSections(in: UITableView) -> Int { return 2 } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let rect = CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 44) let footerView = UILabel(frame:rect) footerView.text = sect[section] return footerView } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 44 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return section == 0 ?lang.count:os.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let arr = indexPath.section == 0 ? lang:os let a = UITableViewCell(style: .default, reuseIdentifier: nil) a.textLabel?.text = String(describing:arr[indexPath.row]) return a } }
代碼建立了三個類,其中的AppDelegate和以前的並無什麼不一樣,Page繼承於UIViewController,也和以前的代碼相似,只是在載入時把Table做爲子視圖加入進來。要特別介紹的是Table。ruby
Table繼承於UITableView,並實現UITableViewDataSource,UITableViewDelegate,在配合代碼:app
self.dataSource = self self.delegate = self
就指明瞭UITableView的數據源對象爲Table,委託對象也是Table。前者指明此對象是UITableView的數據提供者,後者指明此對象是UITableView的外觀和行爲的提供者。ide
具體數據提供的方法就是在此類內實現方法:函數
func numberOfSections(in: UITableView) -> Int { return 2 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return section == 0 ?lang.count:os.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let arr = indexPath.section == 0 ? lang:os let a = UITableViewCell(style: .default, reuseIdentifier: nil) a.textLabel?.text = String(describing:arr[indexPath.row]) return a }
第一個方法告訴TableView此列表共有兩個區間要去顯示。第二個方法告訴TableView此列表每一個區間的行數,第三個方法告訴TableView指定的區間和行數的內容是什麼。優化
做爲UITableView的外觀和行爲的提供者,具體體現是實現了這些方法:
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let rect = CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 44) let footerView = UILabel(frame:rect) footerView.text = sect[section] return footerView } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 44 }
第一個方法爲指定的區間建立一個頭視圖,第二個方法指示指定區間的行高。
協議UITableViewDataSource,UITableViewDelegate還有不少能夠實現的方法,具體參考iOS的開發者參考資料。
類UITableView不但能夠顯示內容,還能夠配合不少操做。這些內容的操做的基本流程就是修改數據源,而後通知TableView從新裝入。代碼入下:
import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { self.window = UIWindow(frame: UIScreen.main.bounds) let page = Page() page.view.backgroundColor = .blue self.window!.rootViewController = page self.window?.makeKeyAndVisible() return true } } class Page: UIViewController { var a : Table! override func viewDidLoad() { super.viewDidLoad() a = Table() a.frame = CGRect(x: 0,y: 50,width: 300,height: 500) self.view.addSubview(a) } } class Table : UITableView,UITableViewDataSource,UITableViewDelegate{ var sect = NSMutableArray.init(array: ["Lang","OS"]) var lang = NSMutableArray.init(array: ["java","swift","js"]) var os = NSMutableArray.init(array:["Windows","OS X","Linux"]) var t = Timer() var count = 0 override init(frame: CGRect, style: UITableViewStyle) { super.init(frame:frame,style:style) self.dataSource = self self.delegate = self t.invalidate() t = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.update), userInfo: nil, repeats: true); } required init?(coder aDecoder: NSCoder) { super.init(coder:aDecoder) } func update() { if count == 0 { os[0] = "Win" }else if count == 1 { os.add("FreeBSD") }else if count == 2 { lang.removeObject(at: 0) } count += 1 if count >= 3 { t.invalidate() } self.reloadData() } func numberOfSections(in: UITableView) -> Int { return sect.count } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let rect = CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 44) let footerView = UILabel(frame:rect) footerView.text = String(describing: sect[section]) return footerView } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 44 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return section == 0 ?lang.count:os.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let arr = indexPath.section == 0 ? lang as NSArray :os as NSArray let a = UITableViewCell(style: .default, reuseIdentifier: nil) a.textLabel?.text = String(describing:arr[indexPath.row]) return a } }
此代碼和上一節的代碼相比,不一樣在於:
以前的計算機語言數組和操做系統數據被改爲了可變的數組,由於在這個代碼中,咱們須要修改數據來驗證對UITableView的修改
在Table的init函數內,建立一個Timer,它每秒激發一個定時器事件,在不一樣的激發次數中,分別對數據作修改、添加、刪除
調用reload方法,從而讓UITableView從新加載數據
能夠本身添加按鈕並執行對UITableView的列表的刪除和重排。可是也可使用它本身提供了刪除和重排的UI。刪除流程是這樣的:
用戶設置UITableView爲編輯模式
系統在當前內容的基礎上,加上刪除按鈕(內容左側,紅色的減號圖標),以及重排按鈕(內容右側)
用戶能夠選擇點擊刪除按鈕,系統向左推移內容,顯示一個delete按鈕
用戶點擊delete按鈕,系統就會調用程序員實現的委託對象的函數:func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath:
IndexPath)
重排流程是這樣的:
用戶設置UITableView爲編輯模式
系統在當前內容的基礎上,加上刪除按鈕(內容左側,紅色的減號圖標),以及重排按鈕(內容右側)
用戶能夠選擇按住拖動重排按鈕,系統可視化這樣拖動過程
用戶拖動完成,系統就會調用程序員實現的委託對象的函數: func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath)
代碼以下:
import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { self.window = UIWindow(frame: UIScreen.main.bounds) let page = Page() page.view.backgroundColor = .blue self.window!.rootViewController = page self.window?.makeKeyAndVisible() return true } } class Page: UIViewController { var a : LangTableRowOper1? override func viewDidLoad() { super.viewDidLoad() a = LangTableRowOper1() a!.frame = CGRect(x: 0,y: 200,width: 300,height: 200) self.view.addSubview(a!) let b = UIButton() b.setTitle("edit", for: UIControlState()) b.backgroundColor = UIColor.red b.addTarget(self, action: #selector(ViewController.edit(_:)), for: .touchDown) let e = UIButton() e.setTitle("Done", for: UIControlState()) e.backgroundColor = UIColor.blue e.addTarget(self, action: #selector(Page.done(_:)), for: .touchDown) let sv = UIStackView() sv.backgroundColor = UIColor.gray sv.axis = UILayoutConstraintAxis.horizontal sv.distribution = .equalCentering; sv.alignment = .center; sv.spacing = 10; sv.frame = CGRect(x: 0,y: 100,width: 300,height: 50) sv.addArrangedSubview(b) sv.addArrangedSubview(e) sv.translatesAutoresizingMaskIntoConstraints = true self.view.addSubview(sv) } func edit( _ b : UIButton!){ a!.setEditing(true, animated: true) } func done( _ b : UIButton!){ a!.setEditing(false, animated: true) } } class Table : UITableView,UITableViewDataSource,UITableViewDelegate{ var arr = NSMutableArray.init(array: ["java","swift","js"]) override init(frame: CGRect, style: UITableViewStyle) { super.init(frame:frame,style:style) self.dataSource = self self.delegate = self } required init?(coder aDecoder: NSCoder) { super.init(coder:aDecoder) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return arr.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let a = UITableViewCell(style: .default, reuseIdentifier: nil) a.textLabel?.text = String(describing: arr[indexPath.row]) return a } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete{ arr.removeObject(at: indexPath.row) // http://stackoverflow.com/questions/21870680/invalid-update-invalid-number-of-rows-in-section-0 self.deleteRows(at: [indexPath], with: UITableViewRowAnimation.fade) } } func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { return true; } func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { let s = sourceIndexPath.row let d = destinationIndexPath.row let temp = arr[s] arr.removeObject(at: s) arr.insert(temp, at: d) } }
注意,代碼中:
func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { return true; }
此函數須要實現,從而告訴UITableView那些行是能夠拖動重排的。這裏所有返還true,表示全部內容均可以重排。
除了顯示section和row以外,TableView能夠加入表頭表位,節頭節尾,幫助程序員更好的組織內容。
咱們如今來展現了一個有兩個section,每一個section有行的界面。經過代碼加入了表頭表尾、節頭節尾。以下:
import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { self.window = UIWindow(frame: UIScreen.main.bounds) let page = Page() page.view.backgroundColor = .blue self.window!.rootViewController = page self.window?.makeKeyAndVisible() return true } } class Table : UITableView,UITableViewDataSource{ let arrs = [["Row 1","Row 2"],["Row 1"]] let titles = ["Section Title 1","Section Title 2"] let footers = ["Section Footer 1","Section Footer 2"] let tableheader = "Table Header" let tablefooter = "Table Footer" convenience init(){ self.init(frame: CGRect.zero, style:UITableViewStyle.grouped) } override init(frame: CGRect, style: UITableViewStyle) { super.init(frame:frame,style:style) self.dataSource = self self.tableHeaderView = UIView() self.tableHeaderView!.frame = CGRect(x: 0, y: 0,width: 200,height: 20) let l = UILabel() l.text = tableheader l.frame = CGRect(x: 0, y: 0,width: 200,height: 20) self.tableHeaderView?.addSubview(l) self.tableFooterView = UIView() self.tableFooterView!.frame = CGRect(x: 0, y: 0,width: 200,height: 20) let f = UILabel() f.text = tablefooter f.frame = CGRect(x: 0, y: 0,width: 200,height: 20) self.tableFooterView?.addSubview(f) } required init?(coder aDecoder: NSCoder) { super.init(coder:aDecoder) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return arrs[section].count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{ let a = UITableViewCell(style: UITableViewCellStyle.value1, reuseIdentifier: nil) a.textLabel?.text = String(arrs[indexPath.section][indexPath.row]) return a } func numberOfSections(in tableView: UITableView) -> Int{ return arrs.count } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String?{ return titles[section] } func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String?{ return footers[section] } } class Page: UIViewController { var a : Table! override func viewDidLoad() { super.viewDidLoad() a = Table() a.frame = CGRect(x: 0,y: 30,width: 300,height: 400) self.view.addSubview(a) } }
這裏比較特別的是,函數
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String?{ return titles[section] }
告訴TableView,每一個指定section的頭標題。
func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String?{ return footers[section] }
告訴TableView,每一個指定section的尾標題。
類UITableView支持對每一個行作標記和取消標記,標記能夠有多種。其中比較經常使用的是打對號圖標。以下代碼,演示瞭如何對每一個行打對號和取消打對號:
import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { self.window = UIWindow(frame: UIScreen.main.bounds) let page = Page() page.view.backgroundColor = .blue self.window!.rootViewController = page self.window?.makeKeyAndVisible() return true } } class Table : UITableView,UITableViewDataSource,UITableViewDelegate{ let arr = ["java","swift","js"] override init(frame: CGRect, style: UITableViewStyle) { super.init(frame:frame,style:style) self.dataSource = self self.delegate = self } required init?(coder aDecoder: NSCoder) { super.init(coder:aDecoder) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return arr.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let a = UITableViewCell(style: .default, reuseIdentifier: nil) a.textLabel?.text = String(arr[indexPath.row]) return a } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){ print("did select \(indexPath.row)") self.deselectRow(at: indexPath, animated: false) if self.cellForRow(at: indexPath)?.accessoryType != .checkmark{ self.cellForRow(at: indexPath)?.accessoryType = .checkmark }else{ self.cellForRow(at: indexPath)?.accessoryType = .none } } } class Page: UIViewController { var a : Table! override func viewDidLoad() { super.viewDidLoad() a = Table() a.frame = CGRect(x: 0,y: 30,width: 300,height: 400) self.view.addSubview(a) } }
運行起來後,可看到三個行,點擊任何一個行都會顯示對號標記在行尾,再點擊一次就會取消此標記。查詢UITableViewCellAccessoryType的官方文檔能夠獲得更多的標記類型。
在以前的代碼中,每次調用到函數:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
須要一個UITableViewCell實例時,都是採用臨時建立的方式。若是建立的UITableViewCell實例比較多時,能夠經過重用已經建立的UITableViewCell實例來提升效率。作法就是:
註冊一個UITableViewCell類,指定其的重用標識符
經過重用標識符建立實例
UIKit會在內部對此過程優化。實例代碼以下:
import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { self.window = UIWindow(frame: UIScreen.main.bounds) let page = Page() page.view.backgroundColor = .blue self.window!.rootViewController = page self.window?.makeKeyAndVisible() return true } } class Table: UITableView,UITableViewDataSource{ let arr = ["javascript","delphi"] let MyIdentifier = "cell" override init(frame: CGRect, style: UITableViewStyle) { super.init(frame:frame,style:style) self.dataSource = self self.register(UITableViewCell.self, forCellReuseIdentifier: MyIdentifier) } required init?(coder aDecoder: NSCoder) { super.init(coder:aDecoder) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return arr.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let a = tableView.dequeueReusableCell(withIdentifier: MyIdentifier)! a.textLabel?.text = String(arr[indexPath.row]) return a } } class Page: UIViewController { var a : Table! override func viewDidLoad() { super.viewDidLoad() a = Table() a.frame = CGRect(x: 0,y: 30,width: 300,height: 400) self.view.addSubview(a) } }
以前的代碼,建立的Cell都是簡單文字;實際上,每一個Cell均可以做爲一個容器,裝入更多的元素。以下代碼展現了一個複合的Cell的建立:
import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { self.window = UIWindow(frame: UIScreen.main.bounds) let page = Page() page.view.backgroundColor = .blue self.window!.rootViewController = page self.window?.makeKeyAndVisible() return true } } class Table : UITableView,UITableViewDataSource{ let arr = ["java","swift","js"] override init(frame: CGRect, style: UITableViewStyle) { super.init(frame:frame,style:style) self.dataSource = self } required init?(coder aDecoder: NSCoder) { super.init(coder:aDecoder) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return arr.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let a = UITableViewCell(style: .default, reuseIdentifier: nil) a.textLabel?.text = String(arr[indexPath.row]) let s = UISwitch() s.frame = CGRect(x: 0,y: 0,width: 20,height: 20) s.addTarget(self, action: #selector(Table.action(_:)), for: .valueChanged) s.isOn = true a.accessoryView = s return a } func action(_ sender : UISwitch!){ print(sender.isOn) } } class Page: UIViewController { var a : Table! override func viewDidLoad() { super.viewDidLoad() a = Table() a.frame = CGRect(x: 0,y: 30,width: 300,height: 400) self.view.addSubview(a) } }
本案例在每一個Cell中添加了一個UISwitch按鈕,而且能夠如同通常的UIView同樣的響應此按鈕的事件。
能夠沒必要本身定製Cell樣式,而是直接使用系統提供的,這樣你能夠經過設置不一樣的UITableViewCellAccessoryType、文字、文字一、圖片、UITableViewCellStyle而讓Cell外觀變得豐富多彩:
import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { self.window = UIWindow(frame: UIScreen.main.bounds) let page = Page() page.view.backgroundColor = .blue self.window!.rootViewController = page self.window?.makeKeyAndVisible() return true } }
class Page: UIViewController { var a : Table! override func viewDidLoad() { super.viewDidLoad() a = Table() a.frame = CGRect(x: 0,y: 30,width: 300,height: 400) self.view.addSubview(a) } }
class Row { var text : String = "" var text2 : String = "" var image : UIImage var access : UITableViewCellAccessoryType var style : UITableViewCellStyle init( text : String ,text2:String ,image:UIImage,access:UITableViewCellAccessoryType,style : UITableViewCellStyle){ self.text = text self.text2 = text2 self.image = image self.access = access self.style = style } } class Table: UITableView,UITableViewDataSource{ let arr = [ Row( text:"java", text2:"old plain", image:UIImage.imageWithColor(UIColor.red), access:UITableViewCellAccessoryType.checkmark, style: UITableViewCellStyle.value1), Row( text:"ruby", text2:"new cool slow", image:UIImage.imageWithColor(UIColor.green), access:UITableViewCellAccessoryType.detailButton, style: UITableViewCellStyle.value2), Row( text:"swift", text2:"new cool quick ", image:UIImage.imageWithColor(UIColor.blue), access:UITableViewCellAccessoryType.detailDisclosureButton, style: UITableViewCellStyle.subtitle) ] override init(frame: CGRect, style: UITableViewStyle) { super.init(frame:frame,style:style) self.dataSource = self } required init?(coder aDecoder: NSCoder) { super.init(coder:aDecoder) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return arr.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let a = UITableViewCell(style: arr[indexPath.row].style, reuseIdentifier: nil) a.textLabel?.text = arr[indexPath.row].text a.detailTextLabel?.text = arr[indexPath.row].text2 a.imageView?.image = arr[indexPath.row].image a.accessoryType = arr[indexPath.row].access return a } } extension UIImage { class func imageWithColor(_ color: UIColor) -> UIImage { let rect = CGRect(x: 0.0, y: 0.0, width: 10.0,height: 10.0 ) UIGraphicsBeginImageContext(rect.size) let context = UIGraphicsGetCurrentContext() context?.setFillColor(color.cgColor) context?.fill(rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image! } }
案例顯示了三行,每行有不一樣的風格組合,都是經過設置UITableViewCellAccessoryType、文字、文字一、圖片、UITableViewCellStyle來達成的。你能夠實際運行此代碼,瞭解不一樣樣式的差別。能夠經過官方手冊查詢UITableViewCellStyle和UITableViewCellAccessoryType的不一樣選擇。這裏列出的類爲UIImage擴展出來的方法:
class func imageWithColor(_ color: UIColor) -> UIImage
是爲了避免必尋找圖片,而能夠即席按需建立出能夠用於實例的圖片,傳遞不一樣的顏色值,能夠獲得不一樣顏色的小方塊圖片。咱們只是須要展現Cell的顯示圖片的能力,所以只有經過代碼建立出圖就好,沒必要爲此單獨尋找適合工程使用的圖片。
咱們一直使用UITableView,把它加入到一個ViewController內,而後由AppDelegate加載後者。實際上,可使用UITableViewController直接由AppDelegate加載:
import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { self.window = UIWindow(frame: UIScreen.main.bounds) let page = LangTableViewController() page.view.backgroundColor = .blue self.window!.rootViewController = page self.window?.makeKeyAndVisible() return true } } class LangTableViewController : UITableViewController{ let arr = ["swift","obj-c","ruby"] let MyIdentifier = "cell" override func viewDidLoad() { super.viewDidLoad() tableView.register(UITableViewCell.self, forCellReuseIdentifier: MyIdentifier) } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return arr.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let a = tableView.dequeueReusableCell(withIdentifier: MyIdentifier) a!.textLabel?.text = arr[indexPath.row] return a! } }
和UITableView的使用的不一樣之處,在於:
原本須要實現UITableViewDataSource和UITableViewDelegate的方法,如今已經有UITableViewController實現,做爲UITableViewController的子類,新類須要的是覆蓋父類的方法。
使用UITableViewController會自動把UITableView填滿AppDelegate.window視圖內。無需程序員指定位置和大小。