首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用UISwitch的UITableView

使用UISwitch的UITableView
EN

Stack Overflow用户
提问于 2015-08-20 14:44:32
回答 3查看 2.2K关注 0票数 2

我使用故事板和自动布局。当我选择first UISwitch并向下滚动时,我看到other UISwitch也打开了,如果我向上滚动,我的第一个UISwitch就会关闭。如何解决这个问题?

我的代码:

代码语言:javascript
复制
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";



    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

    }


    UISwitch* switchView = (UISwitch *)[cell viewWithTag:5];

    [switchView addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged];

       return cell;

}
EN

回答 3

Stack Overflow用户

发布于 2015-08-20 15:06:15

这是因为UITableView重用了UITableViewCell,所以一个单元可以在不同的indexPaths中多次使用,在这种情况下,您有责任维护UITableViewCell subViews的状态。更好的做法是在cellForRowAtIndexPath中返回单元格添加逻辑,以显示/隐藏UISwitch或选择准确的状态,即打开或关闭,您可以将该标志保留在dataSource对象中,然后可以检查该标志,以便为UISwitch设置正确的状态

票数 3
EN

Stack Overflow用户

发布于 2015-08-20 15:15:03

试试这个:

代码语言:javascript
复制
 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        static NSString *CellIdentifier = @"CellSetting";

        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
        cell.textLabel.text = [self.settingsArray objectAtIndex:indexPath.row];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

        if ([[self.settingsArray objectAtIndex:indexPath.row] isEqualToString:ROW_PRIVATE_BROWSING])
        {
            self.privateBrowsingSwitch =[[UISwitch alloc]initWithFrame:CGRectMake(cell.frame.size.width-65, 10, 30, 30)];
            if (ApplicationDelegate.privateBrowsing)
            {
                [self.privateBrowsingSwitch setOn:YES animated:YES];
            }
            [self.privateBrowsingSwitch addTarget:self action:@selector(changeSwitch:) forControlEvents:UIControlEventValueChanged];
            [cell addSubview:self.privateBrowsingSwitch];
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
        return cell;
    }
票数 3
EN

Stack Overflow用户

发布于 2015-08-20 15:11:25

每次调用cellForRowAtIndexPath时,您都必须替换需要为该位置的单元格显示的特定数据。这包括标签、图片和你的UISwitch。

这是因为UITableViews使用了少量可重用的单元。

在cellForRowAtIndexPath中添加如下内容:

代码语言:javascript
复制
switchView.on = [self isSwitchOnForCellAtIndexPath:indexPath]

然后编写确定开关是否应该打开所需的任何逻辑。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32111245

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档