UITableViewCell - 接收Stepper实例值

时间:2014-04-24 14:08:54

标签: ios objective-c uitableview

我已经设置了一个UITableViewController,它使用健身属性填充自定义单元格 - 简介要求用户能够输入“实际”内容。如果他们超过/错过了他们的taget值 - 我为此添加了一个步进器 - 步进器连接到自定义单元.h文件 - 它又连接到uitableviews .m文件。

我很难理解如何将更改后的值传递回uitableviewcontroller,我怎么知道哪个实例传递了值??

enter image description here

2 个答案:

答案 0 :(得分:3)

这些方面的东西......

    - (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
    {
        MyCustomCell* cell = [tableView dequeueReusableCellForIdentifier:MyCustomCellIdentifier];
        // If newly created cell we need to add a target
        if (![[cell.stepperControl allTargets] containsObject:self])
        {
            [cell.stepperControl addTarget:self action:@selector(stepped:) forControlEvents:UIControlEventValueChanged];
        }

        cell.stepperControl.tag = indexPath.row + indexPath.section * 10000;

        // Rest of configuration...

        return cell;
    }

    - (void)stepped:(UIStepper*)stepper
    {
        int row = stepper.tag % 10000;
        int section = stepper.tag / 10000;

        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:section];

        // Now you know which row was changed so get the cell
        MyCustomCell *cell = (MyCustomCell*)[self.tableView cellForRowAtIndexPath:indexPath];

        // Read required data from the cell through custom properties...

    }

答案 1 :(得分:0)

您可以创建UITableViewController的子类并将步进器实际值存储在数组中,如下所示:

@interface CustomTableViewController () 
// Add property for storing steppers' current values
@property (nonatomic, strong) NSMutableArray stepperValues;

@end

@implmentation CustomTableViewController 

- (instancetype)init {
    self = [super init];
    if (self) {
        // Initiate array with default values
        self.stepperValues = [NSMutableArray arrayWithCapacity:numberOFCells];
        for (int i = 0; i < numberOfCells; i++) {
            [self.stepperValues addObject:@(0)];
        }
    }
    return self;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    // Init cell here
    // ...
    // Set last saved value
    cell.stepper.value = [self.stepperValues[indexPath.row] doubleValue];

    // Save stepper's row for retrieving it in valueChanged: method
    cell.stepper.tag = indexPath.row;

    // Add action for handling value changes
    [cell.stepper addTarget:self action:@selector(stepperValueChanged:) forControlEvents:UIControlEventValueChanged];
    return cell;
}

- (void)stepperValueChanged:(UIStepper *)sender {
    // Replace old stepper value with new one
    [self.stepperValues replaceObjectAtIndex:sender.tag withObject:@(sender.value)];
}

@end

通过此代码stepperValues将包含实际值,您可以将其用于您的目标。