如何在TableView中更改UISwitch的位置

时间:2012-11-01 16:51:52

标签: iphone objective-c ios xcode

我有一个包含UISwitch的TableView。这些开关稍微偏离屏幕。如何正确显示。

Switch

这是我显示开关的代码。

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier = @"POICell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    if(!cell){

    //set the cell text to the
    cell.textLabel.text = [self.catNames objectAtIndex:[indexPath row]];
    NSString *toggle = [self.toggleArray objectAtIndex:[indexPath row]];
    //add switch
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    UISwitch *switchView = [[UISwitch alloc] initWithFrame:CGRectZero];
    cell.accessoryView = switchView;

    if ([toggle isEqualToString: @"OFF"]) {
        [switchView setOn:NO animated:NO];
    }else{
        [switchView setOn:YES animated:NO];
    }


    [switchView addTarget:self action:@selector(switchChanged: ) forControlEvents:UIControlEventValueChanged];
    // Configure the cell...

    }
    return cell;
}

2 个答案:

答案 0 :(得分:1)

我不是将UISwitch添加到标准单元格,而是创建一个包含文本标签和开关的自定义UITableViewCell。

但在查看Apple文档后,您希望实现的目标似乎是一种有效的方法。

Table View Programming Guide for iOS

你的代码看起来很像这样的问题:How to create a UITableViewCell with a UISwitch and get the data?所以我不确定为什么UISwitch没有按预期显示。

答案 1 :(得分:-1)

我认为默认的accessoryView的位置无法移动而没有问题,因为TableViewCell会在很多情况下重新发布它。

因此将其添加为子视图可​​能是更好的主意,而不是尝试" hack"默认行为。