2013-03-11 52 views
1

我试着去一个UISwitch加起来也只有一个单元格在我的表视图继承人的代码:添加UISwitch只有一个单元格中的TableView

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    FormCell *cell = (FormCell *) [tableView dequeueReusableCellWithIdentifier: @"FormCell"]; 
    if(cell == nil) cell = [[FormCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"FormCell"]; 

    if(indexPath.row == 3) 
    { 
     UISwitch *mySwitch = [[UISwitch alloc] initWithFrame:CGRectMake(100, 9, 50, 50)]; 
     [mySwitch addTarget: self action: @selector(flip:) forControlEvents:UIControlEventValueChanged]; 
     [cell.contentView addSubview:mySwitch]; 

     [[UISwitch appearance] setOnTintColor:[UIColor colorWithRed:163.0/255.0 green:12.0/255.0 blue:17.0/255.0 alpha:1.0]]; 
    } 

    return cell; 
} 

其工作,问题是,当我滚动tableview中向上或向下,它重复的UISwitch,但最终还是在表视图的开始...

任何帮助吗?

+0

我们可以得到更多'tableView:heightForRowAtIndexPath'吗? – Larme 2013-03-11 19:43:36

+0

@Larme为了更好的理解而编辑。 – darkman 2013-03-11 20:01:38

回答

0

记住单元格被重用。你最好用自己的标识符创建一个自定义的UITableViewCell。在那里做你自己的鼓励。

+0

我比试图“清理”通用可重用单元更好。向表中添加第二个UITableViewCell,给它自己的标识符,并且当调用get-cell-for-row时返回该单元格,如果行== 3。那样,该单元格只用于第3行。需要请注意,如果要在代码中添加开关而不是在故事板中多次添加开关对象,请务必小心。 – 2013-03-11 19:54:26

0

UITableView高度优化,其中一个主要优化是尽可能重用表格单元对象。这意味着您的表格行和UITableViewCell对象之间不存在永久性的一对一映射。

因此,单元对象的同一个实例可以重复用于多行。一旦单元格的行在屏幕外滚动,该行的单元格将进入“回收”堆,并可能重新用于其他屏幕上的行。

通过创建交换机对象并将其添加到细胞,每次排三,三生屏幕上你重新加入,到任何Cell对象表碰巧“出列”的第3行

如果您将要添加的东西到可重用的单元格中时,必须有相应的代码将Cell重新用于其他表格行时将其重置为默认值的相应代码。

0
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ 
    FormCell *cell = (FormCell *) [tableView dequeueReusableCellWithIdentifier: @"FormCell"]; 

    if(cell == nil){  
     cell = [[FormCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"FormCell"]; 
    } 
else 
    { 
    for (UIView *subview in [cell subviews]) 
    { 
     [subview removeFromSuperview]; 
    } 
    } 

if(indexPath.row == 3) 
{ 
    UISwitch *mySwitch = [[UISwitch alloc] initWithFrame:CGRectMake(100, 9, 50, 50)]; 
    [mySwitch addTarget: self action: @selector(flip:) forControlEvents:UIControlEventValueChanged]; 
    [cell.contentView addSubview:mySwitch]; 

    [[UISwitch appearance] setOnTintColor:[UIColor colorWithRed:163.0/255.0 green:12.0/255.0 blue:17.0/255.0 alpha:1.0]]; 
} 

return cell; 
} 

这不会复制在桌子上滚动 另一种方法是设置reuseIdentifiernil的UISwitch。 希望这有助于。

相关问题