我有我的 UITableViewCell 我使用的子类 UISwitch 作为 accessoryView 以这种方式:
mySwitch = [[UISwitch alloc] initWithFrame:CGRectZero];
self.accessoryView = mySwitch;
一切都好!该应用程序工作正常。

现在我需要添加一些 UIImageView 开关上方,所以我想"好吧,让我们做一个自定义的accessoryView!":
UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 10.0f, 100.0f, 60.0f)];
...
mySwitch = [[UISwitch alloc] initWithFrame:CGRectMake(0.0f, 22.0f, 94.0f, 27.0f)];
[myView addSubview:mySwitch];
self.accessoryView = myView;
[myView release];

一切似乎都可以,但有一个奇怪的行为。当我打开另一个viewcontroller并返回表时,开关神秘地改变了。..
这不是数据管理的问题,而只是在单元格重绘中。..求你了,帮帮我,我能做什么?

提前致谢

有帮助吗?

解决方案 2

嗯。..我发现了问题所在。..它没有链接到表重绘。..
UIControlEventValueChanged 选择器检索开关值和单元格 indexPath.row 以这种方式:
UISwitch *tempSwitch = (UISwitch *)sender;
UITableViewCell *cell = (UITableViewCell *)[tempSwitch superview];

然后它更新保存在 NSMutableArray (tableview的datasource)

但现在开关不是accessoryView,而是accessoryView的子视图,因此对象以不可预测的方式更新。我一秒钟就解决了 superview 信息。

对不起,我的错误,并感谢所有。..

其他提示

发生这种情况是因为单元格被重复使用。因此,如果您将子视图添加到单元格的内容视图,然后在该单元格在另一行中重用后,该视图将出现在该行中。避免这种情况的最好方法是将NSArray保存在包含所有自定义视图(带有子视图)的表的数据源(通常是视图控制器)中。那么你可以这样做:

-(UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*) indexPath {
    NSInteger row = indexPath.row;
    static NSString* cellIdentifier = @"Trololo";

    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier: cellIdentifier];
    if( !cell ) {       
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier: cellIdentifier] autorelease];
    }

    [[cell.contentView subviews] makeObjectsPerformSelector: @selector(removeFromSuperview)];
    [cell.contentView addSubview: [_your_cell_views objectAtIndex: row]];

    return cell;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top