Objective-C (iOS): ボタンのクリックと反応

iOSシミュレータのスクリーンショット 2013.01.03 12.35.00

Objective-C: UIButtonViewController.h

#import <UIKit/UIKit.h>

@interface UIButtonViewController : UIViewController

@end

Objective-C: UIButtonViewController.m

#import "UIButtonViewController.h"

@interface UIButtonViewController ()

@end

@implementation UIButtonViewController

UIImageView *imageView_;
UIButton *button_;

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIImage *image = [UIImage imageNamed:@"sample"];
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
    imageView.frame = CGRectMake(50,150,image.size.width,image.size.height);
    [self.view addSubview:imageView];
    imageView_ = imageView;
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button.frame = CGRectMake(50, 50, 150, 50);
    [button setTitle:@"画像を非表示" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(buttonWasTapped:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    button_ = button;
}

- (void)buttonWasTapped:(UIButton *)button
{
    if (imageView_.hidden) {
        imageView_.hidden = NO;
        [button_ setTitle:@"画像を非表示" forState:UIControlStateNormal];
    } else {
        imageView_.hidden = YES;
        [button_ setTitle:@"画像を表示" forState:UIControlStateNormal];
    }
}

@end