開始用Swift開發iOS 10 - 6 創建簡單的Table Based App


table view應該是iOS應用中最常用的UI element。最好的例子就是iPhone自帶的一些應用,如電話,郵件,設置等。TED,Google+,Airbnb,微信等等都是很好例子。

創建一個項目

  • 項目名稱為SimpleTable,模板為"Single View application"

設計UI

  • 選中Main.storyboard,從Object library中拖動Table View進入視圖
  • 改變Table View的大小至整個view,修改屬性Prototype Cells為1
  • 選中Table View Cell,修改StyleBasicIdentifierCell。table view cell的標準類型有 basic、right detail、left detail 和 subtitle,當然還有定制類型custom。
  • 選中Table View,設置四個spacing約束,上下左右的距離都設置為0

為UITableView添加兩個協議

  • Object library中的每一UI component都是對應一個class,如 Table View就是對應UITableView。可以通過點擊并懸停在UI component上查看對應的class和介紹。
  • ViewController.swift文件的UIViewController后,添加代碼, UITableViewDataSource, UITableViewDelegate,表示ViewController類實現了UITableViewDataSourceUITableViewDelegate兩個協議。
    出現紅色感嘆號,這是xcode的問題提示,點擊參看問題描述:

Type 'ViewController' does not conform to protocol
'UITableViewDataSource'

問題描述為ViewController不符合協議UITableViewDataSource。通過command+點擊 (最新的xcode9變成了command+option+點擊)到UITableViewDataSource中看看你:

public protocol UITableViewDataSource : NSObjectProtocol {

    
    @available(iOS 2.0, *)
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int

    
    // Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
    // Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)
    
    @available(iOS 2.0, *)
    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell

    
    @available(iOS 2.0, *)
    optional public func numberOfSections(in tableView: UITableView) -> Int // Default is 1 if not implemented

    
    @available(iOS 2.0, *)
    optional public func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? // fixed font style. use custom view (UILabel) if you want something different

    @available(iOS 2.0, *)
    optional public func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String?

    
    // Editing
    
    // Individual rows can opt out of having the -editing property set for them. If not implemented, all rows are assumed to be editable.
    @available(iOS 2.0, *)
    optional public func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool

 ...
  • UITableViewDataSource協議中定義了很多方法,除了前兩個方法沒有optional其它都有,有的表示這個方法不一定要實現,沒有的就一定要實現,把這個兩個方法實現了,問題提示就會消失。這兩個方法從名字和返回值類型也大概能知道做了什么:

    • public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int 一個section有幾行,也就是一個section有幾個UITableViewCell, section就是一組UITableViewCell的意思,Table View可以定義多個section,默認是一個。
    • public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 返回每一行的 UITableViewCell
  • ViewController.swift中定義一個變量restaurantNames,類型是數組,表示一系列餐館的名字。

var restaurantNames = ["Cafe Deadend", "Homei", "Teakha", "Cafe Loisl", "PetiteOyster", "For Kee Restaurant", "Po's Atelier", "Bourke Street Bakery", "Haigh'sChocolate", "Palomino Espresso", "Upstate", "Traif", "Graham Avenue Meats AndDeli", "Waffle & Wolf", "Five Leaves", "Cafe Lore", "Confessional","Barrafina", "Donostia", "Royal Oak", "CASK Pub and Kitchen"]
  • 定義UITableViewDataSource的兩個方法:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // 1
        return restaurantNames.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) ->
        UITableViewCell {
        // 2
        let cellIdentifier = "Cell"
        let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier,
                                                     for: indexPath)
        // 3
        cell.textLabel?.text = restaurantNames[indexPath.row]
        return cell
            
    }
  • 1 餐館的數目就是section的行數
  • 2 "Cell"與之前定義的UITableViewCellIdentifier屬性是對應的。dequeueReusableCell方法是產生一個UITableViewCell
  • 3 UITableViewCell中有可算屬性textLabel,其實就是一個UILabel,由于是可選屬性,調用時也用可選鏈式調用cell.textLabel?.text

連接 DataSource 和 Delegate

運行app,沒有數據顯示。盡管上面已經在代碼中讓ViewController繼承了UITableViewDataSource, UITableViewDelegate,但storyboard并不知道。

  • 在document outline中選擇Table View,使用control-dragView Controller,在彈出框中選擇dataSource。同樣的方法選擇delegate
  • 確認連接是否成功。選中Table View,在connetion檢查器中查看;或者直接在document outline中右擊Table View
  • 運行app


添加圖片到Table View

  • simpletable-image1.zip下載圖片,解壓后一起拖到asset catalog
  • ViewController.swifttableView(_:cellForRowAtIndexPath:)方法的return cell前添加代碼cell.imageView?.image = UIImage(named: "restaurant")。使每個UITableViewCell的image都是一樣的。

隱藏狀態欄

頂部狀態來和table view 數據重疊了,只要在ViewController加一段代碼就可以:

override var prefersStatusBarHidden: Bool {
    return true
}

prefersStatusBarHidden是父類UIViewController中的屬性,所以要加 override,表示重寫了。

不同的Cell對應不同的圖片

  • simpletable-image2.zip下載圖片,解壓后一起拖到asset catalog
  • 修改ViewController.swifttableView(_:cellForRowAtIndexPath:)為:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) ->
        UITableViewCell {
        let cellIdentifier = "Cell"
        let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier,
                                                     for: indexPath)
        // Configure the cell...
        let restaurantName = restaurantNames[indexPath.row]
        cell.textLabel?.text = restaurantName
        // 1
        let imageName = restaurantName.lowercased().replacingOccurrences(of: " ", with: "")
        if let image = UIImage(named: imageName) {
            cell.imageView?.image = image
        } else {
            cell.imageView?.image = UIImage(named: "restaurant")
        }
        
        return cell
            
    }
  • 1 把菜館名字字符串先修改成小寫,然后去空格
  • 最終結果

代碼

Beginning-iOS-Programming-with-Swift

說明

此文是學習appcode網站出的一本書 《Beginning iOS 10 Programming with Swift》 的一篇記錄

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,461評論 6 532
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,538評論 3 417
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,423評論 0 375
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,991評論 1 312
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,761評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,207評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,268評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,419評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,959評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,782評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,983評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,528評論 5 359
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,222評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,653評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,901評論 1 286
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,678評論 3 392
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,978評論 2 374

推薦閱讀更多精彩內容