基於Swift的iOS應用程序開發:使用表格顯示並控制數據(一):顯示數據

關於如何使用Swift開發iOS應用程序,並且使用表格來顯示數據,這一點在蘋果官方給出的入門實例程序中已經有了最基本的介紹了:

點擊這裏查看蘋果官方入門教程

本篇僅對錶格的基本應用做一個簡單的整理

1、在storyboard中創建一個UITableViewController容器

這一步非常容易,從Object Library中用鼠標拖動一個Table View Controller控件到storyboard上就可以了:



在“Document Outline”中選中“Table View Cell”,然後在xcode右側的屬性編輯器中可以修改表格的行高:

2、爲表格中的每一行編輯佈局

從Object Library中,選擇你所需要的組件,直接用鼠標拖動到story board上的Table View Controller中即可。在這裏,我就只拖動了一個Label組件:

可以看到,目前爲止在整個storyboard中,我們並不關心表格裏會有多少行數據。實際上,只要我們做好了一行的佈局,那這個表格中的每一行都將會重複這一佈局。
我個人認爲這其實很能體現iOS開發中的一種比較固定的設計思想,這種思想更偏重於ui設計人員,而不是編程人員。

3、創建類和相關代碼

其實所有的UIViewController都需要有一個類與之一一對應,這也是蘋果官方所宣稱的iOS編程中的“mvc”思想-----作爲一個Java/Web程序員,我覺得這與我所理解的“mvc”略有不同。
作爲表格容器,這一步其實可以分爲兩個步驟來進行:

3.1、爲Table View Controller綁定Controller類

這一步其實非常簡單了,就不特別說明了

import UIKit

class DemoTableViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 0
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return 0
    }

    /*
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)

        // Configure the cell...

        return cell
    }
    */

    /*
    // Override to support conditional editing of the table view.
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            // Delete the row from the data source
            tableView.deleteRows(at: [indexPath], with: .fade)
        } else if editingStyle == .insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
記得在storyboard中選中個你的Table View Controller,然後在xcode右側的屬性面板中爲它綁定類

3.2、爲表格中的每一行建立模型類

這是使用表格容器的一個特殊的步驟,我們需要自行創建一個類,這個類必須繼承UITableViewCell:

import UIKit

class DemoTableViewCell: UITableViewCell {

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

創建了類之後,還需要在storyboard中,爲表格行綁定這個類:

然後爲這個表格行設置一個id,我們在代碼階段會用到這個id:



最後,在表格行對應的代碼中,完成組件的定義:



4、在表格中顯示數據

按照蘋果官方入門實例的做法,我們首先在TableViewController類中定義一個數組,來模擬需要顯示在表格中的數據:
class DemoTableViewController: UITableViewController {
    
    /*
     *  在這個數組中,包含了所有需要在表格中顯示的數據
     */
    let stringArr:[String] = ["第一行","第二行","第三行"]

    //...

}

注意這個類中的“numberOfSection”方法,這個方法返回一個Int值,這個值代表在整個界面上我們需要把表格劃分爲多少個分區。大部分應用程序的表格可能都不會劃分太多分區,所以只需要返回“1”就可以了:
override func numberOfSections(in tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
}

然後再來看下面這個方法:
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return 0
}
這個方法也返回一個Int值,這個值代表在每一個不同的表格分區當中,表格的行數。因爲只有一個分區,所以我們只要返回數據數組的長度就可以了:
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return self.stringArr.count
}

最後來看最關鍵的 一個方法:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)

    // Configure the cell...

    return cell
}
xcode的自動代碼生成器默認是將這個方法註釋掉的,所以你需要找到這段註釋,然後開放它:

將註釋開放之後,我們需要對自動生成的代碼做一點點小的調整。首先是修改withIdentifier參數,將這個參數的值改爲storyboard中我們爲表格行所設定的id:
let cell = tableView.dequeueReusableCell(withIdentifier: "demoTableViewCell", for: indexPath)
然後 使用as關鍵字將這個cell對象類型轉換成我們自己所定義的表格行對象:
let cell = tableView.dequeueReusableCell(withIdentifier: "demoTableViewCell", for: indexPath) as! DemoTableViewCell
注意這個方法的參數列表中,有一個名爲“cellForRowAt indexPath”的參數,實際上,這個參數指出的是表格中的每一行的索引號。利用這個索引號,我們可以從數組中找到每一行要顯示的數據:
let content:String = self.stringArr[indexPath.row]
拿到數據之後,就可以將數據賦值到表格行裏去了:
cell.labelDemo.text = content
所以整個方法看起來是這樣的:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "demoTableViewCell", for: indexPath) as! DemoTableViewCell

    let content:String = self.stringArr[indexPath.row]
        
    cell.labelDemo.text = content
        
    return cell
}


到此爲止,表格上就可以顯示內容了。而所有上述這些步驟全部都是與蘋果官方給出的入門實例一樣。後續我會再接着整理一些更爲深入的對錶格的應用。






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章