2014年6月30日 星期一

UITableView programmatically using Swift language(Simple)

【說明】

此份筆記是根據ISBN:978-986-201-900-9這本書的第3章節所紀錄的。

此份筆記為UITableView的最基本建立,其Table的資料是用固定的Array去存取。

首先要使用TableView可將TableView的物件拖曳到Storyboard內,並將TableView的dataSouce與delegate與ViewController做連結,如下圖所示。

將TableView拖曳進Storyboard內
將TableView的dataSource與ViewController做連接
將TableView的delegate與ViewController做連接

TableView必須繼承UITableViewDelegateUITableViewDataSource才可使用。

2014/07/01更新:將每個cell都加入相同的圖片。

【片段程式碼】

var recipes: String[] = ["Egg Benedict", "Mushroom Risotto", "Full Breakfast", "Hamburger", "Ham and Egg Sandwich", "Creme Brelee", "White Chocolate Donut", "Starbucks Coffee", "Vegetable Curry", "Instant Noodle with Egg", "Noodle with BBQ Pork", "Japanese Noodle with Pork", "Green Tea", "Thai Shrimp Cake", "Angry Birds Cake", "Ham and Cheese Panini"]
建立一個名為recipes的Array並將內容輸入好。

func tableView(_tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
    return recipes.count
}
這個func為TableView必須實作的func之一,主要是告訴ViewController表格中有幾列,上面的程式將會回傳recipes這個陣列的個數。

func tableView(_tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
        
    var simpleTableIdentifier: String = "SimpleTableCell"
    var cell = _tableView.dequeueReusableCellWithIdentifier(simpleTableIdentifier) as? UITableViewCell
    if cell == nil {
        cell = UITableViewCell(style: .Default, reuseIdentifier: simpleTableIdentifier)
    }
        
    cell!.imageView.image = UIImage(named: "creme_brelee.jpg")
    cell!.textLabel.text = recipes[indexPath.row]
        
    return cell
}
這個func也是必須實作的,這樣ViewController才知道要如何顯示資料。這個func主要是告訴ViewController每一列要顯示的資料是什麼。

【完整程式碼】

//
//  ViewController.swift
//  SimpleTable
//
//  Created by Hsu,Yi-Sheng on 2014/6/30.
//  Copyright (c) 2014 yisheng. All rights reserved.
//

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    var recipes: String[] = ["Egg Benedict", "Mushroom Risotto", "Full Breakfast", "Hamburger", "Ham and Egg Sandwich", "Creme Brelee", "White Chocolate Donut", "Starbucks Coffee", "Vegetable Curry", "Instant Noodle with Egg", "Noodle with BBQ Pork", "Japanese Noodle with Pork", "Green Tea", "Thai Shrimp Cake", "Angry Birds Cake", "Ham and Cheese Panini"]
                            
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
    
    func tableView(_tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
        return recipes.count
    }
    
    func tableView(_tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
        
        var simpleTableIdentifier: String = "SimpleTableCell"
        var cell = _tableView.dequeueReusableCellWithIdentifier(simpleTableIdentifier) as? UITableViewCell
        if cell == nil {
            cell = UITableViewCell(style: .Default, reuseIdentifier: simpleTableIdentifier)
        }
        
        cell!.imageView.image = UIImage(named: "creme_brelee.jpg")
        cell!.textLabel.text = recipes[indexPath.row]
        
        return cell
    }

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


}


【執行結果】

    

2014/07/01更新:

2014年6月26日 星期四

UIDatePicker programmatically using Swift language

【說明】

此份筆記僅注重於日期的部分,UIDatePicker還有包含時間的部分。
UIDatePicker的建立可以使用Storyboard產生,讓物件與ViewController做連結即可,如下所示。


【片段程式碼】

myDatePicker.datePickerMode = .Date
DatePickerMode有四種列舉型別可以選擇:TimeDateDateAndTimeCountDownTimer
Time
Date
DateAndTime
CountDownTimer
@IBAction func valueChanged(sender: UIDatePicker) {
        

}
當使用Storyboard建立value改變時觸發的func後就會自動產生這段程式碼。

var currentDate: NSDate = myDatePicker.date
建立一個資料型態為NSDate的變數,存放DatePicker的時間。

var dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = .FullStyle
var showDateString: String = dateFormatter.stringFromDate(currentDate)
若我們欲將使用者選擇的日期顯示在UILabel上則可以用NSDateFormatter將時間轉換成String,首先建立一個名為dataFormatter的變數,其資料型態為NSDateFormatter,並設定dateStyle,dateStyle有五種可以選擇:NoStyleShortStyleMediumStyleLongStyleFullStyle,最後用String的變數將轉換後的字串儲存起來。
ShortStyle
MediumStyle
LongStyle
FullStyle

【完整的程式範例】

//
//  ViewController.swift
//  UIDatePicker
//
//  Created by Hsu,Yi-Sheng on 2014/6/26.
//  Copyright (c) 2014 yisheng. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    
    @IBOutlet var myLabel: UILabel
    @IBOutlet var myDatePicker: UIDatePicker
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        myDatePicker.datePickerMode = .Date
    }

    @IBAction func valueChanged(sender: UIDatePicker) {
        
        var currentDate: NSDate = myDatePicker.date
        
        var dateFormatter = NSDateFormatter()
        dateFormatter.dateStyle = .FullStyle
        var showDateString: String = dateFormatter.stringFromDate(currentDate)
        
        myLabel.text = showDateString
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}


【執行結果】

2014年6月25日 星期三

UISwitch programmatically using Swift language

【說明】

若要快速偵測UISwitch的動作可以借助Storyboard的協助,如下所示。


與Stoyboard連結後會自動產生程式碼,在其func內撰寫程式碼即可。

【片段程式碼】

@IBAction func valueChange(sender: UISwitch) {
    if mySwitch.on {
        showLabel.text = "The switch is on."
    } else {
        showLabel.text = "The switch is off."
    }
}

可以在自動產生的func內撰寫程式碼偵測動作,透過UISwitch內的method:on,可以知道UISwitch是否為開啟的狀態。

【完整的程式範例】

//
//  ViewController.swift
//  UISwitch
//
//  Created by Hsu,Yi-Sheng on 2014/6/26.
//  Copyright (c) 2014 yisheng. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
                            
    @IBOutlet var showLabel: UILabel
    @IBOutlet var mySwitch: UISwitch
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
    
    @IBAction func valueChange(sender: UISwitch) {
        if mySwitch.on {
            showLabel.text = "The switch is on."
        } else {
            showLabel.text = "The switch is off."
        }
    }

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

【執行結果】




2014年6月23日 星期一

UIPickerView programmatically using Swift language

【說明】

要使用UIPickerView必須要繼承UIPickerViewDataSource, UIPickerViewDelegate這兩個類別,在Storyboard放入Picker View的物件,並設IBOutlet,如下圖。


dataSource與delegate也要將Outlets設定View Controller上面,如下圖。


【片段程式碼】

func numberOfComponentsInPickerView(_: UIPickerView) -> Int {
        return 1
}
設定有幾個元件在PickerView裡面,此範例設定為1。

func pickerView(_: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return 5
}
設定每個元件有幾個row,範例設定5個,表示有五個選項可以滑動選擇。

func pickerView(_pickerView: UIPickerView!, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString! {
        
    let stringColor = UIColor(red: 255, green: 0, blue: 0, alpha: 1)
    let attributes = [NSForegroundColorAttributeName: stringColor]
    let showString = NSMutableAttributedString(string: "\(stringValue[row])", attributes: attributes)
        
    return showString
}
這個func是在設定選項裡面的內容,上面程式碼回傳的是NSMutableAttributedString,showString 會夾帶String與attribute給UIPickerView。

func pickerView(_: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    switch row {
        case 0...4:
            myLabel.text = "Your choose is \(stringValue[row])."
        default:
            nil
    }
}
這個func是對應到當PickerView的值被更動的時候所對應的動作。

【完整的程式範例】

//
//  ViewController.swift
//  UIPickerView
//
//  Created by Hsu,Yi-Sheng on 2014/6/23.
//  Copyright (c) 2014 yisheng. All rights reserved.
//

import UIKit

class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
                            
    @IBOutlet var pickerView: UIPickerView
    @IBOutlet var myLabel: UILabel
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
    
    //設定有幾個元件
    func numberOfComponentsInPickerView(_: UIPickerView) -> Int {
        return 1
    }
    
    //設定每個元件中有幾個row
    func pickerView(_: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return 5
    }
    
    var stringValue: String[] = ["A", "B", "C", "D", "E"]
    
    //顯示PickerView內的資料
    func pickerView(_pickerView: UIPickerView!, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString! {
        
        let stringColor = UIColor(red: 255, green: 0, blue: 0, alpha: 1)
        let attributes = [NSForegroundColorAttributeName: stringColor]
        let showString = NSMutableAttributedString(string: "\(stringValue[row])", attributes: attributes)
        
        return showString
    }
    
    //PickerView變更的時候所做的動作
    func pickerView(_: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        switch row {
            case 0...4:
                myLabel.text = "Your choose is \(stringValue[row])."
            default:
                nil
        }
    }

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


}


【執行結果】

       

2014年6月20日 星期五

UIAlertView programmatically using Swift language

【說明】

方法可能都會變動,畢竟現在(2014/06/20)還在beta階段,一切以Apple公布為主。

適用於iOS 8.0 或之後

UIAlertController 取代了UIActionSheetUIAlertView,顯示AlertView的方式使用presentViewController:animated:completion:

【片段程式碼】

var alertView = UIAlertController(title: "Example to show alert", message: "Test on UIAleryView", preferredStyle: .Alert)
宣告一個名為alertView的物件,並設定AlertView顯示的title以及說明的文字,並使用Alert的樣式去顯示,如下圖所示。

preferredStytle的選擇有兩種:ActionSheet、Alert,上面的範例使用的是Alert,若是使用ActionSheet則為下圖所示。


alertView.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
設定alertView的動作,按鈕的文字設為OK,使用的樣式為預設,UIAlertActionStytle有三種樣式:Default、Cancel、Destructive,處理的程序設為無。

self.presentViewController(alertView, animated: true, completion: nil)
叫ViewController顯示alertView在頁面上,使用動畫的方式顯示設為是,完成時不做任何動作。

alertView.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: cancel))
若要偵測按鈕的動作需有個func讓Action可以去執行,如上面程式碼所示。

func cancel(alertView: UIAlertAction!) {
        println("You cancel it")

    }
當使用者按下Cancel按鈕後就會去執行名為cancel的func,而cancel的func程式碼如下。

【完整的程式範例】


//
//  ViewController.swift
//  UIAlertView
//
//  Created by Hsu,Yi-Sheng on 2014/6/20.
//  Copyright (c) 2014 yisheng. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    
    @IBOutlet var myButton: UIButton
                            
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        myButton.addTarget(self, action: "buttonPress:", forControlEvents: .TouchUpInside)
    }
    
    func buttonPress(sender: UIButton!) {
        
        var alertView = UIAlertController(title: "Example to show alert", message: "Test on UIAleryView", preferredStyle: .Alert)
        
        alertView.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: cancel))
        alertView.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
        
        
        self.presentViewController(alertView, animated: true, completion: nil)
    }
    
    func cancel(alertView: UIAlertAction!) {
        println("You cancel it")
    }

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


}

【執行結果】