2011/10/27

10/27/2011 - 2 comments

文字輸入 Hello World (xcode 4.2 iOS5)

本篇很單純,只將文字key進去,顯示在label上。

首先開啟新的project,選擇Single View Application。

現在預設會啟動「Use Storyboard」和「Use Automatic Reference Counting」。這部份也不用改,Storyboard就是新版的xib,ARC則是由程式自動控制記憶體釋放。特色可參考官網解釋

開好檔案後,在MainStoryboard.storyboard拉Label和TextField。


接著在ViewController.h放入Label和TextField:

1
2
3
4
5
6
7
8
9
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController <UITextFieldDelegate> {  
    IBOutlet UILabel *myLabel;
    IBOutlet UITextField *myTextField;
}

@property (nonatomic, strong) UILabel *myLabel;
@property (nonatomic, strong) UITextField *myTextField;
@end


在ViewController.m的@implementation ViewController下方寫:

1
2
3
4
5
6
7
8
@synthesize myLabel, myTextField;

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    //將文字送到myLabel,並釋放鍵盤。
  myLabel.text = myTextField.text;  
  [myTextField resignFirstResponder];
  return YES; 
}

接著回storyboard將關係拉起來:

分別是
myLabel 和 Label - Label
myTextField 和 TextField
以及在 Referencing Outlet的 delegate 和 TextField 。



拉好後就可以run囉,只要在上面輸入完文字後,按Return就會自動將文字送到Label了。

2 意見:

  1. 請問一下,要如何顯示本文第一張圖片中 "View Controller Scene" 區域,我直接點選 storyboard 會出現一堆程式碼~

    回覆刪除
    回覆
    1. 你是不是有切到右上角的Editor按鈕?
      Editor要選"Show the standard editor",如果你原本是用"Show the version editor"會看到程式碼。

      刪除