2014-10-11 39 views
0

我的应用程序有50个按钮。我想以编程方式将图像添加到按钮到所有按钮。如何将图像添加到多个按钮

我声明通过出口按钮作为

@property (strong, nonatomic) IBOutlet UIButton *radiobtn1; 
@property (strong, nonatomic) IBOutlet UIButton *radiobtn2; 
@property (strong, nonatomic) IBOutlet UIButton *radiobtn3. 
. 
. 
@property (strong, nonatomic) IBOutlet UIButton *radiobtn50; 

这是我的阵列

NSMutableArray *allButtons; 
allButtons = [[NSMutableArray alloc] init]; 
allButtons = [NSMutableArray arrayWithObjects:@"radiobtn1", .....,@"radiobtn50",nil]; 

这是我的逻辑

for (i = 0; i <= 50; i++) 
{ 

[self.allbuttons[i] setImage:[UIImage imageNamed:@"radioButtonDisabled.png"]  forState:UIControlStateSelected]; 
} 



but application is crashing with exception 'NSInvalidArgumentException', reason: '-[__NSCFConstantString setImage:forState:]: unrecognized selector sent to instance 0x16d4c' 
+0

将“<=”更改为“<”, – 2014-10-11 07:37:40

回答

2

在你有字符串类型值和setImage所有按钮阵列方法为UIButton类型的对象,不适用于NSString类型。这就是为什么你的代码崩溃。

试试这个代码来创建多个按钮,并添加到浏览 -

float leftMargin = 20; 
float topMargin = 20; 

for (int i=0 ; i<9; i++) { 

UIButton *BtnObj   = [[UIButton alloc]initWithFrame:CGRectMake(leftMargin, topMargin,100,40)]; 
    [BtnObj setBackgroundImage:[UIImage imageNamed:@"imageName.png"] forState:UIControlStateNormal]; 
    [BtnObj setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; 
    [BtnObj addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside]; 
    [self.view addSubview:BtnObj]; 

    topMargin += 50; 
} 

和方法被称为 -

-(void)buttonClicked:(UIButton *)sender{ 
    NSLog(@"Button clicked"); 
} 

希望这会有所帮助。