本文介绍了UISwitch在UITableView单元格中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 UITableView 单元格上嵌入 UISwitch



我现在的解决方案 $ p> UISwitch * mySwitch = [[[UISwitch alloc] init] autorelease];
cell.accessoryView = mySwitch;


解决方案

将其设置为accessoryView通常是。你可以在 tableView:cellForRowAtIndexPath:中设置它。你可能希望在翻转开关时使用target / action来做某事。像这样:

   - (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 = @我有一个开关;
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(@开关是%@,switchControl.on?@ON:@OFF);
}


How can I embed a UISwitch on a UITableView cell? Examples can be seen in the settings menu.

My current solution:

UISwitch *mySwitch = [[[UISwitch alloc] init] autorelease];
cell.accessoryView = mySwitch;
解决方案

Setting it as the accessoryView is usually the way to go. You can set it up in tableView:cellForRowAtIndexPath: You may want to use target/action to do something when the switch is flipped. Like so:

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

这篇关于UISwitch在UITableView单元格中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 09:40