kade

技術系の記事を書いていきます。

Objective-C: UIButtonをxibを使わずに作成する

UIImageViewとかだと動的に作りたいタイミングがあったりするのですが、Buttonはあまりなくて、あれ、IBActionはどうやって紐付けるんだっけ?ってなったのでメモしておきます。

UIButton* btn;
-(void)addButton{
  btn = [UIButton buttonWithType:UIButtonTypeCustom]; // カスタムでボタン初期化
  btn.frame = CGRectMake(30, 30, 50, 50);// x, y, w, h
  UIImage *img = [UIImage imageNamed:@"hoge.png"]; // 画像を指定
  [btn setImage:img forState:UIControlStateNormal]; // 画像をボタンに紐付け
  [btn addTarget:self action:@selector(hoge:) forControlEvents:UIControlEventTouchDown];// touchDownでhogeというメソッドを発火
  [self.view addSubview:btn];
}
-(void)hoge:(id)sender{
  NSLog(@"Touch Down !!");
}