[英]How to add radio button to uitableview?
我在表格視圖單元格中添加了按鈕,當用戶點擊單元格時,我想從所有按鈕中選擇一個按鈕
- (UITableViewCell *)tableView:(UITableView *)theTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = @"cell";
UITableViewCell *cell = [theTableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
_radioButton = [UIButton buttonWithType:UIButtonTypeCustom];
_radioButton.frame = CGRectMake(30, 0, 30, 30);
[_radioButton setImage:[UIImage imageNamed:@"radio_empty.png"] forState:UIControlStateNormal];
[_radioButton setImage:[UIImage imageNamed:@"radio.png"] forState:UIControlStateSelected];
cell.accessoryView = _radioButton;
_radioButton.tag = indexPath.row;
}
if ([indexPath isEqual:selectedIndex])
{
_radioButton.selected = YES;
}
else
{
_radioButton.selected = NO;
}
cell.textLabel.text = [self.Option objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)theTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
selectedIndex = indexPath;
[theTableView reloadData];
//I tried this also but not working
if (_radioButton.tag == indexPath.row) {
[_radioButton setImage:[UIImage imageNamed:@"radio.png"] forState:UIControlStateSelected];
}
}
我試了很多 但這不起作用。 我想在用戶點擊單元格時顯示選定的圖像。 使用按鈕視圖還是圖像視圖
我得到了這樣的解決方案。
NSString *selectedIndex;
- (void)tableView:(UITableView *)theTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[theTableView deselectRowAtIndexPath:indexPath animated:NO];
if(indexPath.row != [selectedIndex intValue]) {
// reset the active account
selectedIndex = [@(indexPath.row) stringValue];
// tell the table to rebuild itself
[theTableView reloadData];
}
}
- (UITableViewCell *)tableView:(UITableView *)theTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = @"cell";
UITableViewCell *cell = [theTableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
if(indexPath.row == [selectedIndex intValue]) {
cell.imageView.image = [UIImage imageNamed:@"radio.png"];
}
else {
cell.imageView.image = [UIImage imageNamed:@"radio_empty.png"];
}
cell.textLabel.text = [self.Option objectAtIndex:indexPath.row];
return cell;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.