2014年6月4日 星期三

iOS 開發筆記 - 初學 Swift 與 Storyboard 互動方式,以 UITableViewController 和 prepareForSegue 為例



WWDC 2014 讓 Swift 出世見人,想學習的可先看 Apple 官網 Swift 文件:The Swift Programming Language,大概只要看完 A Swift Tour 即可有基本功力,看完心得:簡潔有力。接著,就可以看看 Using Swift with Cocoa and Objective-C 這份了,也是此次筆記項目。

首先下載 Xcode 6 beta 下來用,新增 Project 時,選用 Swift 程式語言,這時的程式架構就是 Swift 語法,與 Objective-C 大同小異,初次看還滿清爽的。

AppDelegate:

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
                         
    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
        // Override point for customization after application launch.
        return true
    }

    func applicationWillResignActive(application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(application: UIApplication) {
        // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }

}


ViewController:

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

}


接著,則是使用 Storyboard,承襲之前用 Xcode 開發的模式,新增元件後,可以拖拉到對應的程式碼(此例為 ViewController),就可以填寫一些 Code 了。

例如 UIButton 行為:

    @IBOutlet var button : UIButton
 
    @IBAction func myClick(sender : AnyObject) {
        println("Click")
        button.setTitle("change", forState: UIControlState.Normal);
    }


例如 UITableViewController :

import UIKit

class MyTableViewController: UITableViewController {
    var dataList = String[]()
 
    override func numberOfSectionsInTableView(tableView: UITableView?) -> Int {
        return 1
    }
 
    override func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int {
        return dataList.count
    }
 
    override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
     
        var cell:UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
     
        cell.text = dataList[indexPath.row]
     
        return cell
    }
 
}


以及 prepareForSegue 的用法:

    override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
        if segue.identifier.compare("showTable") == 0 {
            if segue.destinationViewController.isKindOfClass(MyTableViewController) {
                // Type 'AnyObject!' cannot be implicitly downcast to 'UIViewController'
                // var vc:UIViewController = segue.destinationViewController

                var tvc:MyTableViewController = segue.destinationViewController as MyTableViewController
             
                tvc.dataList.append("Hello")
                tvc.dataList.append("World")
            }
        }
    }


以上的小練習,就可以用 Swift 跟 Storyboard 切換 ViewController 等行為,而 UITableViewController 也稍微用了一下。

最後一提,目前使用 Swift 開發的不習慣之處:AutoComplete ! 沒了這招就真的等於砍掉重練了,試用的結果,不是按了 "." 之後會彈跳出來,而是要打 "->" 才會出現 Orz 我想應該還有不少待釐清的用法。

沒有留言:

張貼留言