2012-03-29 8 views
1

ボタンを押すたびにボタンをビューに追加するアクションを実行しようとしています。私が試したことは何もできません。IBActionからプログラムでUIButtonを追加する

誰かが何をすべきかを明確にすることができれば幸いです。

この私のボタンの追加ボタンで最新の試みです:あなたはこの

#import <QuartzCore/CoreAnimation.h> 

を追加する必要が

-(IBAction) addButton{ 
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; 
    button.frame = CGRectMake(10,10,50,50); 
    button.tag = 1; 

    [button addTarget:self 
       action:@selector(buttonTouched:) 
    forControlEvents:UIControlEventTouchUpInside]; 
    [view addSubview:button]; 
} 
+0

このメソッドが呼び出されていますか? – Alexander

+0

IBActionが正しく配線されていることを確認します。時には急いで、アクション/ iboutletsをバインドするのに失敗します... –

+0

また、 'view'が' nil'でないことを確認してください。 – Costique

答えて

6
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
button.frame = CGRectMake(10,10,50,50); 
button.tag = 1; 
[button addTarget:self action:@selector(buttonTouched:) forControlEvents:UIControlEventTouchUpInside]; 
[self.view addSubview:button]; 

Try the above codes. 
+0

'button'のローカル宣言がインスタンス変数を隠しているという警告があります...それは大丈夫ですか? – nfoggia

1

は、この

-(IBAction)buttonTouched:(id)sender{ 
     NSLog(@"New Button Clicked"); 
    } 
    -(IBAction)addButton:(id)sender 
    { 
     UIButton *btnallstates; 
     UIImage *statesbtnimg=[UIImage imageNamed:@"1.png"]; 
     btnallstates=[[UIButton buttonWithType:UIButtonTypeCustom]retain]; 
     btnallstates.tag=1; 
     btnallstates.frame=CGRectMake(103, 127, 193, 31); 
     [btnallstates.layer setBorderWidth:0]; 
     [btnallstates addTarget:self action:@selector(buttonTouched:)  forControlEvents:UIControlEventTouchUpInside]; 
     [btnallstates setBackgroundImage:statesbtnimg forState:UIControlStateNormal]; 
     [self.view addSubview:btnallstates]; 

    } 
1
に従ってください。

あなたのコードは正しいです。唯一のビュー上のボタンを表示するように

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 

にこのライン

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; 

を変更。

UIButtonTypeCustomがビューに追加されても表示されません。

これは、ボタンの色を変更することでわかります。 たとえば、これにコードを変更します。

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; 
button.backgroundColor=[UIColor redColor]; 

希望します。楽しい。

0
Try this 

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
[button addTarget:self 
     action:@selector(aMethod:) 
    forControlEvents:UIControlEventTouchUpInside]; 
[button setTitle:@"Show View" forState:UIControlStateNormal]; 
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0); 
[self.view addSubview:button]; 
関連する問題