从IBAction以编程方式添加UIButton
问题描述:
我试图做出一个操作,每次按下按钮时,都会向视图添加一个按钮。我没有尝试过的作品。从IBAction以编程方式添加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];
}
答
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
有一个警告,说本地声明的'按钮'隐藏实例变量......是好吗? – nfoggia 2012-03-29 15:05:53
答
您需要添加此
#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];
}
答
你的代码是正确的。仅此行
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
改变
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
显示视图上的按钮。
UIButtonTypeCustom
虽然被添加到视图中,但不会显示出来。
你可以通过改变按钮的颜色来理解这一点。 例如将代码更改为此。
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.backgroundColor=[UIColor redColor];
希望它有效。请享用。
答
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];
您确定调用该方法吗? – Alexander 2012-03-29 04:53:39
检查IBAction是否正确接线。有时赶时间,我们错过了绑定动作/ iboutlets ... – 2012-03-29 04:56:10
还要确保'view'不是'nil'。 – Costique 2012-03-29 05:04:24