2014-10-11 82 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"); 
} 

希望這會有所幫助。