从IBAction以编程方式添加UIButton

时间:2012-03-29 04:50:48

标签: iphone uibutton

我试图在每次按下按钮时进行操作,它会在视图中添加一个按钮。我没有尝试过任何工作。

如果有人能够清理该做什么,我将不胜感激。

这是我在按钮添加按钮上的最新尝试:

-(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];
}

4 个答案:

答案 0 :(得分: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.

答案 1 :(得分:1)

你需要添加这个

   #import <QuartzCore/CoreAnimation.h>

然后按照这个

进行操作
 -(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];

  }

答案 2 :(得分:1)

您的代码是正确的。只更改此行

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];

显示视图上的按钮。

UIButtonTypeCustom虽然已添加到视图中,但却未显示。

您可以通过更改按钮的颜色来理解这一点。 例如,将代码更改为此。

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

希望它有效。享受。

答案 3 :(得分: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];
相关问题