如何在UITableView单元上嵌入UISwitch?可以在设置菜单中看到示例.

My current solution:

UISwitch *mySwitch = [[[UISwitch alloc] init] autorelease];
cell.accessoryView = mySwitch;

推荐答案

将其设置为accessoryView通常是一种方法.你可以在tableView:cellForRowAtIndexPath:分钟内设置,当switch 被翻转时,你可能想使用目标/动作来做一些事情.就像这样:

- (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" );
}

Objective-c相关问答推荐

[NSNull new]和[NSNull NULL]有什么不同?

iOS - 如何预加载键盘?

可供学习的 iOS 示例项目

如何获取 AppIcon 的 UIImage?

如何编写 Objective-C 完成块

iOS7过度导航栏按钮填充

dispatch_semaphore_dispose 上的 EXC_BAD_INSTRUCTION(代码=EXC_I386_INVOP,子代码=0x0)

UILabel 的角半径属性在 iOS 7.1 中不起作用

在Objective-C中替换字符串中的一个字符

如何将@selector 作为参数传递?

Cocoa 与 Cocoa Touch - 有什么区别?

iPhone:在 UITextField 上禁用 Auto-Cap/autocorrect 问题

从 NSRange 创建 UITextRange

使用 NSLog 打印 NSData

Objective-C 中的同步和异步调用与多线程有什么区别?

从带有参数的方法名称创建 Select 器

如何获得设备的比例因子?

使用 cocoaLumberjack 将日志(log)文件存储在哪里

公开只读但具有私有设置器的 Objective-C 属性

如何在对象内使用 objc_setAssociatedObject/objc_getAssociatedObject?