我在UITableview中创建了一个UISwitch,但是在确切的行中看不到它。我在项目中引用并实现的代码。谁能告诉我如何更正它。

if (indexPath.row == 1) {

 UISwitch *switchBtn = [[UISwitch alloc] initWithFrame:CGRectMake(200, 10, 150, 50)];
 [switchBtn setOn:YES animated:YES];
 NSInteger row;
 switchBtn.tag=row;
 row =[indexPath row];
 [switchBtn addTarget:self action:@selector(switchStateChanged:) forControlEvents:UIControlEventValueChanged];
 cell.accessoryView = switchBtn;
 [cell addSubview:switchBtn];

 UILabel *lblPhone =[[UILabel alloc]initWithFrame:CGRectMake(5, 5, 230, 30)];
 lblPhone.text = @"Change Default View as Month View";
 lblPhone.font = [UIFont systemFontOfSize:12];
 [cell.contentView addSubview:lblPhone];

}
-(IBAction)switchStateChanged:(id)sender
{
UISwitch *switchState = sender;

if(switchState.tag == 0)
{
     NSLog(@"ON");
}
else {
    NSLog(@"OFF");

    }
 }

最佳答案

参考此代码

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuseIdentifier" forIndexPath:indexPath];
if (indexPath.row == 1) {

    UISwitch *switchBtn = [[UISwitch alloc] init];
    [switchBtn setOn:YES animated:NO];
    switchBtn.tag=[indexPath row];
    [switchBtn addTarget:self action:@selector(switchStateChanged:) forControlEvents:UIControlEventValueChanged];
    cell.accessoryView = switchBtn;
    UILabel *lblPhone =[[UILabel alloc]initWithFrame:CGRectMake(5, 5, 230, 30)];
    lblPhone.text = @"Change Default View as Month View";
    lblPhone.font = [UIFont systemFontOfSize:12];
    [cell.contentView addSubview:lblPhone];

}
// Configure the cell...

return cell;
}
-(void)switchStateChanged:(id)sender
{
UISwitch *switchControl = sender;

if(switchControl.tag == 1)
{
    if (switchControl.isOn) {
        NSLog(@"on");
    }else{
        NSLog(@"off");
    }
}
}


屏幕截图

关于ios - UISwitch在UITableview(iOS 8)中不可见?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30366485/

10-12 14:35