2

我正在尝试构建一个如下所示的 UITableViewCell:

由于我还不能发布图片,我将尝试通过说它是带有 UISwitch(中)和附件(右)的标签(左)来描述它。

希望你能得到图片...

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

我该怎么办?(使开关先得到水龙头)。我猜这是 firstResponder 的事情,但我没有找到我需要的魔法代码。

一旦我通过了这个,我可能会弄清楚我自己的配件的启用/禁用......

谢谢。

4

1 回答 1

1

创建 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 文件的文件所有者,向 UIViewController 添加子类单元的 IBOutlet。使用加载自定义单元格

        [[NSBundle mainBundle] loadNibNamed:@"Your Custom Cell nib file name" owner:self options:nil];

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

于 2011-12-15T17:07:48.387 回答