UIButtonの基本的な使い方をまとめました。画像のボタンではなく通常のボタンで、画面への追加からイベントの分岐までサンプルにまとめています。
下記よりサンプルのダウンロードが行えます。
ダウンロード
ソースコード
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
| @implementation ViewController
enum {
BUTTON_FIRST = 0
};
- (void)viewDidLoad
{
[super viewDidLoad];
[self setButton];
}
//ボタンをセット
- (void)setButton
{
//ボタンを作成
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
//ボタンのテキストを設定
[button setTitle:@"Button" forState:UIControlStateNormal];
//ボタンのテキストに合わせてサイズを自動調整
[button sizeToFit];
//画面の中央に配置
button.center = self.view.center;
//画面が変わってもボタンの位置を自動調整
button.autoresizingMask =
UIViewAutoresizingFlexibleWidth |
UIViewAutoresizingFlexibleHeight |
UIViewAutoresizingFlexibleLeftMargin |
UIViewAutoresizingFlexibleRightMargin |
UIViewAutoresizingFlexibleTopMargin |
UIViewAutoresizingFlexibleBottomMargin;
//ボタンのタグを指定
button.tag = BUTTON_FIRST;
//ボタンをタップした時に指定のメソッドを呼ぶ
[button addTarget:self
action:@selector(buttonDidTap:)
forControlEvents:UIControlEventTouchUpInside];
//ボタンを画面に追加
[self.view addSubview:button];
}
//ボタンのタップイベント
- (void)buttonDidTap:(UIButton *)button
{
//タグを格納
NSInteger eventType = button.tag;
//タグからイベントタイプを取得し振り分け処理
if (eventType == BUTTON_FIRST) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil
message:[NSString stringWithFormat:@"eventType: %d", eventType]
delegate:nil
cancelButtonTitle:nil
otherButtonTitles:@"OK", nil];
[alert show];
}
}
@end
|
お薦めの参考書
絶対に挫折しない iPhoneアプリ開発「超」入門 増補改訂第4版
Swiftについて知りたい開発者の方のみならず、プログラミング未経験者の方にも参考になる内容になっています。Swiftの基礎を一から丁寧に解説されており、この書籍があればネットで調べる手間をかなり省くことができると思います。