-1

我用一些数据制作了一个 UITable,并且我在其中包含了一个 UISwitch,但它在运行时没有显示在表中。

在.h

@interface CalcViewController : UITableViewController {

    IBOutlet UITableView *mainTableView;

    NSMutableArray *courseMURArray;


    NSMutableArray *switchStates;
}

在.m

- (void)viewDidLoad
{
    [super viewDidLoad];

    switchStates = [[NSMutableArray alloc] init ];

    int i = 0;

    for (i = 0; i < 33; i++) {
        [switchStates addObject:@"OFF"];
    }
}

并且在

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];

        UISwitch *theSwitch = nil;


        if (cell == nil) {


            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];

            theSwitch = [[UISwitch alloc]initWithFrame:CGRectZero];
            theSwitch.tag = 100;

            CGRect frame = theSwitch.frame;
            frame.origin.x = 230;
            frame.origin.y = 8;
            theSwitch.frame = frame;

            [theSwitch addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged];


            [cell.contentView addSubview:theSwitch];

        }else{

            theSwitch = [cell.contentView viewWithTag:100];

        }

        if ([[switchStates objectAtIndex:indexPath.row] isEqualToString:@"ON"]) {
            theSwitch.on = YES;
        }else{
            theSwitch.on = NO;
        }

return cell;
}

这是选择器方法

-(void) switchChanged: (UISwitch *) sender{

    UITableViewCell *theParentCell = [[ sender superview] superview];
    NSIndexPath * indexPathOfSwitch = [mainTableView indexPathForCell:theParentCell];

    if (sender.on) {
        [switchStates replaceObjectAtIndex:indexPathOfSwitch.row withObject:@"ON"];
    }else{
        [switchStates replaceObjectAtIndex:indexPathOfSwitch.row withObject:@"OFF"];
    }


}

数据一切正常,但数据没有问题,有什么问题吗?

4

2 回答 2

1

当您为 RowAtIndexPath 设置单元格中的单元格时,您将框架设置为 CGRectZero,即位置 (0,0) 处的矩形,宽度 = 高度 = 0。然后重置位置,但从未重置宽度 &高度。
在您的 2 frame.origin 行之后添加:

  • frame.size.width = XX;
  • frame.size.height = YY;

或者只是使用 CGRectMake(X, Y, width, height) 来制作框架。

于 2012-08-05T00:03:22.070 回答
1

在您的 cellForRowAtIndexPath 中,如果单元格为 nil,则初始化 UISwitch 并将其添加到单元格中。如果单元格最初不是 nil 怎么办?

假设 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"] 返回一个有效的单元格,那么根本不会创建任何开关。

您可能需要验证是否已在界面构建器中指定“Cell”作为 UITableViewCell 的标识符,以防万一。

或者,将用于初始化 UISwitch 的代码移到“if(cell==nil)”之外。看看这是否能解决您的问题。如果 dedequeueReusableCellWithIdentifier: 返回 nil,则“if(cell==nil)”块应该用于初始化单元格。

此外,您为所有开关使用标记号 100,在 else 块中,使用标记 100 的 contentView 初始化 Switch。如果您有多个开关,iOS 应该将哪个 UISwitch 分配给 theSwitch?您可能想参考我关于如何正确设置标签号的帖子。

于 2012-08-06T03:02:40.563 回答