iOSアプリ開発のメモ置き場

ささたつがiOSアプリ開発で知ったObjective-Cのtipsなどを書いていく所存

StoryBoard は使わずに、ボタンをクリックしたときにラベルのテキストを変更する

#import "ViewController.h"

@interface ViewController ()
@property (nonatomic, strong) UILabel *label;
@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    CGRect rect = CGRectMake(10, 10, 100, 100);
    self.label = [[UILabel alloc] initWithFrame:rect];
    self.label.text = @"default";
    [self.view addSubview:self.label];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button.frame = CGRectMake(50, 50, 100, 30);
    [button setTitle:@"click" forState:UIControlStateNormal];

    // ドヤッ
    [button addTarget:self action:@selector(changeTextLabel:) forControlEvents:UIControlEventTouchDown];

    [self.view addSubview:button];
}

- (void)changeTextLabel:(id)sender
{
    self.label.text = @"change";
}

@end