在由步进器控制的单元格中设置一个标签 – 目标c

您好我有一个UITableView,我dymanically插入单元格,其中包含UIStepper和UILabel。 UILabel显示UIStepper的值。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"]; if(!cell) cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"]; [cell.textLabel setText:[self.myarray objectAtIndex:indexPath.row]]; UIStepper *stepper = [[UIStepper alloc]init]; UILabel *label = [[UILabel alloc]init]; label.text = [NSString stringWithFormat:@"%.f", stepper.value]; [cell addSubview:stepper]; [cell addSubview:label]; [stepper addTarget:self action:@selector(incrementStepper:) forControlEvents:UIControlEventValueChanged]; return cell; } 

我已经删除了一些上面的行格式为了clarities而行,但这个工程,一切都很好。

 -(void)incrementSkillStepper:(id)sender { UIStepper *stepper = (UIStepper*)sender; //set the label that is in the same cell as the stepper with index stepper.value. } 

当我点击特定单元格中的步进器时,我希望同一个单元格中的标签递增,但是我的问题是addtarget的工作方式 – 我只能发送发件人,在这种情况下,发件人是事件,意思是它不能访问dynamic创build的标签。 有谁知道我可以如何设置incrementStepper委托方法的标签文本?

调用[sender superview]来获取它所在的单元格,

 -(void)incrementSkillStepper:(id)sender { UIStepper *stepper = (UIStepper*)sender; UITableViewCell* cell = [stepper superview]; UIView* subview = [[cell subviews] lastObject]; // Make sure your label *is* the last object you added. if ([subview isKindOfClass:[UILabel class]]) { // do what you want } } 

你也可以通过[cell.contentView subviews] array循环,获得你需要的标签,最好给标签viewWithTag一个tag值,并使用viewWithTag

您可以将标签设置为indexPath.row并将标签设置为indexPath.row + 999。

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UIStepper *stepper = [[UIStepper alloc]init]; stepper.tag = indexPath.row; UILabel *label = [[UILabel alloc]init]; label.tag = indexPAth.row + 999; //...... } 

现在在UIStepper的委托方法中,您可以像这样在该单元格中find标签

 -(void)incrementSkillStepper:(id)sender { UIStepper *stepper = (UIStepper*)sender; UILabel *label = (UILabel *)[self.view viewWithTag:sender.tag + 999]; //now this is same label as you want. Now you can change the value of label as you want } 

您应该使用步进器的值更新模型,然后根据模型中的值设置标签的值。 你应该给步进器的cellForRowAtIndexPath中的一个标签,它等于indexPath.row,在步进器的操作方法中,将模型中属性的值设置为步进器的值。 然后,重新加载该行在相同的indexPath。

 (void)incrementSkillStepper:(UIStepper *)sender { NSInteger row = sender.tag; [self.theData[row] setObject:@(sender.value) forKey:@"stepperValue"]; [self.tableView reloadRowsAtIndexPaths: @[row] withRowAnimation:UITableViewRowAnimationNone]; } 

在cellForRowAtIndexPath中,你可以用类似的方式填充标签:

  UILabel *label = [[UILabel alloc]init]; label.text = [NSString stringWithFormat:@"%@", self.theData[indexPath.row][@"stepperValue"]]; 

在这个例子中,我假设你有一个字典数组(theData),它有你需要填充单元格的所有数据。 其中一个字典键“stepperValue”将用于将步进值存储为NSNumber。