UITwitch在UITableView单元格中

tes*_*ing 81 iphone cocoa-touch objective-c uitableview uiswitch

我怎样才能UISwitchUITableView细胞上嵌入?可以在设置菜单中看到示例.

我目前的解决方案

UISwitch *mySwitch = [[[UISwitch alloc] init] autorelease];
cell.accessoryView = mySwitch;
Run Code Online (Sandbox Code Playgroud)

zpa*_*ack 192

将它设置为accessoryView通常是要走的路.您可以在其中进行设置tableView:cellForRowAtIndexPath: 您可能希望在切换开关时使用目标/操作来执行某些操作.像这样:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    switch( [indexPath row] ) {
        case MY_SWITCH_CELL: {
            UITableViewCell *aCell = [tableView dequeueReusableCellWithIdentifier:@"SwitchCell"];
            if( aCell == nil ) {
                aCell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"SwitchCell"] autorelease];
                aCell.textLabel.text = @"I Have A Switch";
                aCell.selectionStyle = UITableViewCellSelectionStyleNone;
                UISwitch *switchView = [[UISwitch alloc] initWithFrame:CGRectZero];
                aCell.accessoryView = switchView;
                [switchView setOn:NO animated:NO];
                [switchView addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged];
                [switchView release];
            }
            return aCell;
        }
        break;
    }
    return nil;
}

- (void)switchChanged:(id)sender {
    UISwitch *switchControl = sender;
    NSLog( @"The switch is %@", switchControl.on ? @"ON" : @"OFF" );
}
Run Code Online (Sandbox Code Playgroud)

  • aCell.accessoryView = switchView的好点; (2认同)
  • 怎么知道所选开关的索引? (2认同)
  • @doxsi`opensView.tag = indexPath.row`用于检测哪个行开关更改为swift (2认同)

Ech*_*lon 10

您可以向单元格添加UISwitch或任何其他控件accessoryView.这样它就会出现在单元格的右侧,这可能是你想要的.


kth*_*rat 8

if (indexPath.row == 0) {//If you want UISwitch on particular row
    UISwitch *theSwitch = [[UISwitch alloc] initWithFrame:CGRectZero];
    [cell addSubview:theSwitch];
    cell.accessoryView = theSwitch;
}
Run Code Online (Sandbox Code Playgroud)

  • 我只能通过设置单元格的accessoryView属性来完成这项工作.我不认为将开关添加为子视图是必要的. (2认同)