2014年8月6日 星期三

Storyboard's segue running by coding

【說明】

此份筆記在紀錄如何用寫程式的方式去執行Storyboard的Segue。

執行Segue的五大流程步驟:
Step 1:初始化目標頁面(XML)
Step 2:建立Segue的實體
Step 3:執行來源的prepareForSegue的method。
Step 4:執行Segue的performSegueWithIdentifier的method。
Step 5:釋放Segue的記憶體。

現在我們要將第4步驟抽出用寫程式的方式去呈現執行Segue的動畫,亦即是Push一個頁面到Navigation Controller。


【專案開發步驟】

建立專案:

使用Single View Application模板建立一個名為segueWithCoding的專案,使用iPhone裝置。

設計使用者介面:

將single view加入Navigation Controller,如下圖所示。

加入Navigation Controller
拖曳新的ViewController至Storyboard內,如下圖所示。

加入新的ViewController
建立Segue,並選擇push,如下圖所示。

建立Segue
選擇push
替Segue設定Identifier。

設定Segue的Identifier
用程式建立UIButton:

在ViewDidLoad內撰寫建立UIButton的程式碼,如下所示。

<Swift>
var theButton: UIButton = UIButton(frame: CGRectMake(50, 100, 150, 30))
theButton.setTitleColor(UIColor.redColor(), forState: .Normal)
theButton.setTitle("GoSecondView", forState: .Normal)
theButton.addTarget(self, action: "GoSecondView", forControlEvents: .TouchUpInside)
view.addSubview(theButton)

<Object-C>
UIButton *theButton = [[UIButton alloc] initWithFrame:CGRectMake(50, 100, 150, 30)];
[theButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
[theButton setTitle:@"GoSecondView" forState:UIControlStateNormal];
[theButton addTarget:self action:@selector(goSecondView:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:theButton];

撰寫當按鈕按下後會觸發的func,如下所示。

<Swift>
func goSecondView(sender: UIButton) {
        
}

<Object-C>
-(void)goSecondView:(UIButton*)sender {

}

執行Segue的動畫:

當按鈕按下後要啟動Segue,所以可以透過performSegueWithIdentifier這個method來達成。

<Swift>
func goSecondView(sender: UIButton) {
    performSegueWithIdentifier("goSecondView", sender: nil)
}

<Object-C>
-(void)goSecondView:(UIButton*)sender {
    [self performSegueWithIdentifier:@"goSecondView" sender:nil];
}


【執行結果】

如此一來就可以用程式執行Segue的動畫,但是其餘的步驟還是由XML來完成。

沒有留言:

張貼留言