如何在用户更改UITableViewCell中的值时更新UITableView数据源

时间:2014-10-17 08:50:00

标签: ios uitableview uisegmentedcontrol

Sample Screen

首先,这是一个供老师出席的应用程序,考勤将更新回我的服务器。我的TableViewCell定制如下。

@interface TvcStudentClassSession : UITableViewCell

@property (strong, nonatomic) IBOutlet UILabel *lblStudentInfo;
@property (strong, nonatomic) IBOutlet UISegmentedControl *smgStatus;
@property NSInteger studentId;

@end

我在TableViewCell中为SegmentedControl创建了一个IBAction。选中它后,它应该调用我的webservice并立即更新服务器中的值。这没有问题。

现在的问题是,我的UITableViewCell填充在我的父视图中。代码如下。 objStudentClassSessions 是一个NSMutableArray,用于存储从服务器加载的值。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"tvcStudentClassSession";

    TvcStudentClassSession *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    // Configure the cell...
    ObjStudentClassSession *objStudentClassSession = [objStudentClassSessions objectAtIndex:indexPath.row];

    cell.classSessionId = selectedObjClassSession.classSessionId;
    cell.studentId = objStudentClassSession.studentId;
    cell.lblStudentInfo.text = [NSString stringWithFormat:@"%@ (%@)", objStudentClassSession.studentName, objStudentClassSession.studentCode];

    if([objStudentClassSession.attendanceStatus isEqualToString:STATUS_NONE])
    {
        [cell.smgStatus setSelectedSegmentIndex:0];
    }
    else if([objStudentClassSession.attendanceStatus isEqualToString:STATUS_PRESENT])
    {
        [cell.smgStatus setSelectedSegmentIndex:1];
    }
    else if([objStudentClassSession.attendanceStatus isEqualToString:STATUS_ABSENT])
    {
        [cell.smgStatus setSelectedSegmentIndex:2];
    }

    return cell;
}

每当用户更改SegmentedControl时,IBAction在UiTableViewCell类中成功调用并成功更新到服务器。但是一旦我向下滚动屏幕然后再向上,SegmentedControl就会返回到原始状态,我知道这是iOS的工作方式,它每次加载单元格值都会变得可见。

对于我的情况,我可以知道如何更新UITableView中的 objStudentClassSessions ,以便在单元格再次可见时正确重新加载?

1 个答案:

答案 0 :(得分:1)

您还需要在细分更改时更新本地数据。所以在代码处理部分中这样的事情改变了:

ObjStudentClassSession *objStudentClassSession = [objStudentClassSessions objectAtIndex:indexOfStudentFromSegmentedControl];
objStudentClassSession.attendanceStatus == segentedControl.selectedSegmentIndex == 0 ? ...