我试图将一个按钮添加到tableview中的新单元格中,例如,我需要一个单元格下的按钮' 1'如果昏暗不是0。
但是我无法做到。请赐教。
- (void)viewDidLoad
{
[super viewDidLoad];
_displaynum = [NSArray arrayWithObjects:@"1",@"2",@"3", nil];
_displayID = [NSArray arrayWithObjects:@"ID = 1",@"ID = 2",@"ID = 3", nil];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [_displaynum count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *lightIdentifier = @"lightIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:lightIdentifier];
if (cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:lightIdentifier];
}
UISwitch *switchLights = [[UISwitch alloc] initWithFrame:CGRectMake(1.0, 1.0, 20.0, 20.0)];
cell.textLabel.text = [_displayLights objectAtIndex:indexPath.row];
cell.detailTextLabel.text =[_displayLightsID objectAtIndex:indexPath.row];
cell.accessoryView = switchLights;
switchLights.on = NO;
int dim = 1;
if ((dim =! 0)) {
NSArray *insertIndexPaths = [NSArray arrayWithObjects:
[NSIndexPath indexPathForRow:1 inSection:0],
nil];
NSArray *deleteIndexPaths = [NSArray arrayWithObjects:
[NSIndexPath indexPathForRow:2 inSection:0],nil];
[tableView beginUpdates];
[tableView insertRowsAtIndexPaths:insertIndexPaths withRowAnimation:UITableViewRowAnimationRight];
[tableView deleteRowsAtIndexPaths:deleteIndexPaths withRowAnimation:UITableViewRowAnimationFade];
[tableView endUpdates];
}
return cell;
}
}
答案 0 :(得分:2)
首先,cellForRowAtIndexPath:
不是按照您的方式插入或删除行的正确位置。
cellForRowAtIndexPath:
。因此,在这里您可以修改单元格并简单地返回它。
那就是说,这就是你需要做的事情:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *lightIdentifier = @"lightIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:lightIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:lightIdentifier];
}
int dim = 1;
if (dim != 0 && indexPath.row == 1) {
CGRect buttonRect = CGRectMake(210, 25, 65, 25);
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = buttonRect;
// set the button title here if it will always be the same
[button setTitle:@"Action" forState:UIControlStateNormal];
button.tag = 1;
[button addTarget:self action:@selector(myAction:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:button];
}
return cell;
}