在UITableViewCell中,让UISwitch获得点击,然后accessoryview,如果switch是on的



我试图建立一个UITableViewCell,看起来像这样:

由于我还不能发布图像,我将试着描述它,说它是一个标签(左)与一个UISwitch(中)和配件(右)。

希望你能明白…

的想法是,accessoryView是可见的,但禁用如果开关是关闭的。当用户打开开关时,他们可以点击并向右导航,看到他们可以选择的选项列表。问题是,当开关被轻敲时,细胞得到的是轻敲,而不是开关。

我该怎么做?(要使开关先接通水龙头)。我猜这是一个firstResponder的东西,但我没有找到我需要的神奇代码。

一旦我解决了这个问题,我就可以自己找出配件的启用/禁用…

谢谢。

创建UISwitch控件并将其添加到单元格内容视图中。

    - (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] autorelease];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.accessoryType = (UITableViewCellAccessoryNone;
            UISwitch* aSwitch = [[UISwitch alloc] initWithFrame:CGRectZero];
aSwitch.tag = [indexPath row];
            CGRect rect = cell.frame;
            CGRect switchRect = aSwitch.frame;
            switchRect.origin = CGPointMake( (rect.size.width / 2) - (aSwitch.frame.size.width / 2), 
                                               (rect.size.height / 2) - (aSwitch.frame.size.height / 2));
            aSwitch.frame = switchRect;
            [aSwitch addTarget:self action:@selector(switchSwitched) forControlEvents:UIControlEventValueChanged];
            [cell addSubview:aSwitch];

            [aSwitch release];
        }
        return cell;
    }
    - (void)switchSwitched:(UISwitch*)sender {
        if (sender.on) {
    UITableViewCell* aCell = [self.tableView cellForRowAtIndexPath:
                              [NSIndexPath indexPathForRow:sender.tag inSection:0]];
    aCell.accessoryType = (sender.on == YES ) ? UITableViewCellAccessoryDisclosureIndicator : UITableViewCellAccessoryNone;
        }
    }

你也可以实现这个不同的子类UITableViewCell和添加UITableViewCell nib文件。使UIViewTableController成为Cell nib文件的文件所有者,为子类化的Cell添加一个IBOutlet到UIViewController。使用

加载自定义单元格
        [[NSBundle mainBundle] loadNibNamed:@"Your Custom Cell nib file name" owner:self options:nil];

参见Apple iOS编程指南http://developer.apple.com/library/ios/#documentation/UserExperience/Conceptual/TableView_iPhone/TableViewCells/TableViewCells.html#//apple_ref/doc/uid/TP40007451-CH7

相关内容

最新更新