prettyprint

2017年3月24日 星期五

練習 3:自訂 Table View

1. 新建 Single View Application,之後 delete 此 default 之 UIViewController 與 ViewController.swift 檔案

2. 在 project 的資料夾,新建 New File > Cocoa Touch Class

3. 將此新增 class 與 UI 整合:指定此UI的TableView 的 class 名稱為 WordsTableViewController


4. 指定此為 First Initial Response

5.  將 TableView 的 Style = Basic, Cell Identifier = Cell

6.  修改 code

//
//  WordsTableViewController.swift
//  MyWords
//
//  Created by Elvis Meng on 2017/3/24.
//  Copyright © 2017 Elvis Meng. All rights reserved.
//

import UIKit

class WordsTableViewController: UITableViewController {
    
    var objNames = ["obj1","obj2","obj3","obj4","obj5","obj6","obj7","obj8","obj9","obj10","obj11","obj12","obj13","obj14","obj15","obj16","obj17","obj18","obj19","obj20"]

    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 1
    }

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

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

        // Configure the cell...
        cell.textLabel?.text = objNames[indexPath.row]

        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.
    }
    */


}

7. 告知 data source 的來源


8. 若要加入 image,只要將 image 拖曳至 Access.xcassets 資料夾,然後修改下列 code:


var objNames = ["人間失格","obj2","obj3","obj4","obj5","obj6","obj7","obj8","obj9","obj10","obj11","obj12","obj13","obj14","obj15","obj16","obj17","obj18","obj19","obj20"]

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

        // Configure the cell...
        cell.textLabel?.text = objNames[indexPath.row]
        cell.imageView?.image = UIImage(named: objNames[indexPath.row])

        return cell
    }

測試

/end

練習 2: Simple Table View [Swift 3.0]


1. 新增 Single Table View Project

2. 拖曳 Table View 物件至 View Controller,並設定 Prototype Cell 的值為 1


3. 點選 Table View Cell,設定其 Identifier 的值為 Cell,Style = Basic


4. UITableView 採用 UITableViewDataSource 與 UITableViewDelegate 兩個協定 Protocol


class ViewController: UIViewController, UITableViewDelegate, UITableViewDelegate {}

6. 關於 UITableViewDataSource,我們必須實做的方法:

tableView(_:numberOfRowsInSection:)
tableView(_:cellForRowAtIndexPath:)

完整 ViewController.swift 如下:

//
//  ViewController.swift
//  MySimpleTableViewDemo
//
//  Created by Elvis Meng on 2017/3/23.
//  Copyright © 2017 Elvis Meng. All rights reserved.
//

import UIKit

var objNames = ["obj1","obj2","obj3","obj4","obj5","obj6","obj7","obj8","obj9","obj10","obj11","obj12","obj13","obj14","obj15","obj16","obj17","obj18","obj19","obj20"]

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

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

    func tableView(_ tableView: UITableView, numberOfRowsInSection section:Int) -> Int {
        return objNames.count
    }

    func tableView(_ tableView:UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellIdentifier = "Cell"
        let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath)
        cell.textLabel?.text = objNames[indexPath.row]
        
        return cell
    }
}



7. 整合 UI / Code,將 UI 的 dataSource / delegate 的連接點



8. 測試

點選滑鼠右鍵,然後下拉 scroll down


若要在每個 cell 中顯示圖片 image:

1. 將圖片 image 拖曳至 Access.xcassets 目錄夾中



2. 在 Image View 屬性中,設定 Image 的值為 “英文字母“,此時這 image 加入至 Content View 中 ( 因為 Cell  的 style 為 Basic,其涵 Image View)


3. 修改 Code

import UIKit

var objNames = ["obj1","obj2","obj3","obj4","obj5","obj6","obj7","obj8","obj9","obj10","obj11","obj12","obj13","obj14","obj15","obj16","obj17","obj18","obj19","obj20"]

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

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

    func tableView(_ tableView: UITableView, numberOfRowsInSection section:Int) -> Int {
        return objNames.count
    }

    func tableView(_ tableView:UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellIdentifier = "Cell"
        let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath)
        cell.textLabel?.text = objNames[indexPath.row]
        cell.imageView?.image = UIImage(named: "英文字母")
        
        return cell
    }

}


4. 測試


若想每個 Cell 正確顯示不同的 image,需更改下列 code。別忘了 objNames 中的名稱必須與 image 的命名一致。


var objNames = ["英文字母","英文字母","obj3","obj4","obj5","obj6","obj7","obj8","obj9","obj10","obj11","obj12","obj13","obj14","obj15","obj16","obj17","obj18","obj19","obj20"]

func tableView(_ tableView:UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellIdentifier = "Cell"
        let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath)
        cell.textLabel?.text = objNames[indexPath.row]
        cell.imageView?.image = UIImage(named: objNames[indexPath.row])
        
        return cell
    }

測試:



/end

2017年3月23日 星期四

練習 1: Hello World! [Swift 3.0]

練習 1: Hello World! [Swift 3.0]

1. 新增 Project

Create a new Xcode project  > Single View Application (iOS)

2. Project Settings

Product Name / Team / Organization Name / Organization Identifier / (Bundle Identifier) / Language (Swift) / Devices (iPhone) / Use Core Data (none) / Include Unit Tests (none) / Include UI Tests (none)


3. Save Project Settings


4. 點選 Main.storyboard,拖曳一個 Button至 View Controller 上,更改文字為 Hello World!


5. 新增 UI / Code 連接點 @IBAction : showMessage

點選 Button,按 Control 鍵不放,拖曳至 ViewController 的 Icon 中



6. 在 Send Events 中,點選 showMessage,此時可在 Code 中 出現圓圈的連接點

7. 新增 showMessage() 的 Code

//
//  ViewController.swift
//  HelloWorldDemo
//
//  Created by Elvis Meng on 2017/3/23.
//  Copyright © 2017 Elvis Meng. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    @IBAction func showMessage(){
     print("Hello World!")
    }


}

8.  在模擬 iPhone 中,點選 Hello World! 這Button,會顯示 Hello World ! 這字串在 Debug 視窗中


9. 若想將 Hello World ! 這字串以單獨視窗顯示,而不是顯示在 Debug 視窗

//
//  ViewController.swift
//  HelloWorldDemo
//
//  Created by Elvis Meng on 2017/3/23.
//  Copyright © 2017 Elvis Meng. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    @IBAction func showMessage(){
     //print("Hello World!")
        let alertController = UIAlertController(title: "Alert!", message: "Hello World !", preferredStyle: UIAlertControllerStyle.alert)
        alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
        present(alertController, animated: true, completion: nil)
    }

}



10. 測試結果:



結論:

這是很簡單練習,重點在 Xcode 開發環境熟悉,以及增加 Button 後 UI / Code 如何連接 connection。

點選 Button 後,會觸發 showMessage() 事件。  我們要實作此 code

/end
prettyPrint();