ボタンタッチの検出と、タッチに対するアクションを指定するには、addTarget:action:forControlEventメソッドを用いる。
この時、MyAppDelegateのメッソド内で作成したUIViewControllerのオブジェクトではaddTarget:action:forControlEventメソッドを実行するとエラーとなる。しかし、MyAppDelegateのインスタンス変数としてUIViewControllerのオブジェクトを作成することでaddTarget:action:forControlEventメソッドを実行できる。
MyAppDelegate.h
#import <UIKit/UIKit.h> @interface MyAppDelegate : UIResponder <UIApplicationDelegate> { UIViewController* viewController; } @property (strong, nonatomic) UIWindow *window; @end
MyAppDelegate.m
#import "MyAppDelegate.h" #import "MyViewController.h" @implementation MyAppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; // Override point for customization after application launch. viewController = [[MyViewController alloc] init]; viewController.view.backgroundColor = [UIColor yellowColor]; [self.window addSubview:viewController.view]; self.window.backgroundColor = [UIColor whiteColor]; [self.window makeKeyAndVisible]; return YES; }
MyViewController.h
#import <UIKit/UIKit.h> @interface MyViewController : UIViewController - (void)buttonDidPush; @end
MyViewController.m
#import "MyViewController.h" @interface MyViewController () @end @implementation MyViewController - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self; } - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(20, 20, 200, 100)]; label.backgroundColor = [UIColor greenColor]; label.text = @"らべるてきすと"; [self.view addSubview:label]; UITextView* textView = [[UITextView alloc] initWithFrame:CGRectMake(20, 130, 200, 100)]; textView.backgroundColor = [UIColor whiteColor]; [self.view addSubview:textView]; UIButton* button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; button.frame = CGRectMake(230, 20, 80, 50); [button setTitle:@"ボタン" forState:UIControlStateNormal]; [button addTarget:self action:@selector(buttonDidPush) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:button]; } - (void)buttonDidPush { NSLog(@"----ログ1----"); } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
コメント