2017-08-02 162 views
0

我正在使用單選按鈕,爲此我正在編寫這樣的代碼。當我們點擊一​​個按鈕時如何改變圖像?

float x = 40; 
float y = 0; 
for (int i=0; i<self.radioBtnTagArr.count; i++) { 

     self.radioButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
     self.radioButton.frame = CGRectMake(x, y+35, 35.0, 35.0); 
     [self.radioButton setImage:[UIImage imageNamed:@"radio_empty.png"] forState:UIControlStateNormal]; 
     [self.radioButton addTarget:self action:@selector(radioBtnMethod:) forControlEvents:UIControlEventTouchUpInside]; 
     [self.scrollView addSubview:self.radioButton]; 
     self.radioButton.tag = [[self.radioBtnTagArr objectAtIndex:i] intValue]; 

     y = y+70; 

    } 

這種「self.radioBtnTagArr」來自服務器(標記來自服務器),根據該計數我想創建單選按鈕和我指定標籤是標籤,以單選按鈕。

- (void) radioBtnMethod:(UIButton *)sender { 

for (int i=0; i<self.radioBtnTagArr.count; i++) { 

    if (sender.tag == [[self.radioBtnTagArr objectAtIndex:i] intValue]) { 

     [self.radioButton setImage:[UIImage imageNamed:@"radio.png"] forState:UIControlStateSelected]; 

     [self.radioButton setSelected:YES]; 

    } 

} 
} 

現在的問題是,當我點擊第一個單選按鈕的最後一個單選按鈕被選中這樣下面的圖片...

Radio button image

我想只有當我們點擊第一個按鈕,第一個按鈕狀態選擇,如果我們點擊第二個按鈕第二個按鈕狀態選擇像這樣...

+0

你可以在這裏https://stackoverflow.com/questions/44618690/dynamic-radio-buttons-uitableview-custom-cell-ios/44632164#44632164 – vp2698

回答

1

確實像創建另一個數組保存UIbutton,例如

步驟-1

@property (nonatomic, strong) NSMutableArray *buttonArray; 

步驟-2

添加所有按鈕buttonArray

// allocate the memory for your array 
    buttonArray = [NSMutableArray array]; 

for (int i=0; i<self.radioBtnTagArr.count; i++) { 
     // create instance value of UIButton 
     UIButton *radioButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
     radioButton.frame = CGRectMake(x, y+35, 35.0, 35.0); 
     [radioButton setImage:[UIImage imageNamed:@"radio_empty.png"] forState:UIControlStateNormal]; 
     [radioButton addTarget:self action:@selector(radioBtnMethod:) forControlEvents:UIControlEventTouchUpInside]; 
     [self.scrollView addSubview:self.radioButton]; 

     y = y+70; 
     // add the object to array 
     [buttonArray addObject:radioButton]; 

    } 

步驟-3

目標內部

- (void) radioBtnMethod:(UIButton *)sender { 

    // reset the previous selection 
    for (UIButton *getradioButton in buttonArray) { 
     [getradioButton setImage:[UIImage imageNamed:@"radio_empty.png"] forState:UIControlStateNormal]; 
} 
    // set the current selection 
    [sender setImage:[UIImage imageNamed:@"radio.png"] forState:UIControlStateNormal]; 

} 
+0

檢查我的回答是,它的工作感謝ü老兄.. .. – iOS

+0

@iOSDeveloper - 歡迎兄弟 –

+0

@ Anbu.Karthik https://stackoverflow.com/questions/45453747/parsing-array-of-json-inside-object-in-swift –

相關問題