2012年8月26日 星期日

動態產生 UIViewController (ㄧ)

一個自己實驗的範例: 使用empty template 來動態產生 UIViewController,不使用Storyboard

 Xcode版本4.4.1

1.  先產生一個新專案,Template當然使用Empty



2.  Project名稱取為DynamicUIViewController, Class叫做Main

3.專案的檔案列表如圖


4. 新增加一個新的Class檔,這是要給動態產生UIViewController用的。

5. MainAppDelegate.h程式碼如下

#import <UIKit/UIKit.h>
#import "MainViewController.h"

@interface MainAppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@property (strong, nonatomic) MainViewController *mvc;

@end

6. MainAppDelegate.m程式碼修改如下
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
   
    self.mvc = [[MainViewController alloc] init];
   
    [self.window addSubview:self.mvc.view];
   
    [self.window makeKeyAndVisible];
    return YES;
}

7. MainViewController.h修改如下

@interface MainViewController : UIViewController
{
    UIButton *button;
}

@property (nonatomic, retain) IBOutlet UIButton *button;

-(id) init;
-(IBAction)touch;

@end







8. MainViewController.m增加程式碼如下
@interface MainViewController ()

@end

@implementation MainViewController

@synthesize button;

-(id) init{
    self = [super init];
   
    if (self) {
        button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [button addTarget:self action:@selector(touch) forControlEvents:UIControlEventTouchUpInside];
        [button setTitle:@"Click Me" forState:UIControlStateNormal];
        button.frame = CGRectMake(60, 60, 100, 40);
        [self.view addSubview:button];
       
    }
   
    return self;
}

- (IBAction)touch{
   
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"展示結果" message:@"你按了按鈕" delegate:nil cancelButtonTitle:@"結束" otherButtonTitles:nil];
    [alert show];
}

9. 完成以上程式修改,執行結果如下