使用自定义单元格编辑模式

时间:2011-10-27 11:41:55

标签: objective-c uitableview editing

我使用IB构建自定义单元格,并将其显示在tableView上,但不会覆盖整个窗口。 我设置了toolbar并给它一个按钮,用于切换isEditing属性和按钮标题。我还在if(!self.editing)中制作了didSelectRowAtIndexPath

我收到反馈,当按下按钮时,我处于编辑模式,但我的自定义单元格没有显示左侧的删除符号。如果我滑动一个单元格,右侧上的删除按钮会出现,但如果我按下该按钮,应用程序会崩溃,但我稍后会解决这个问题,我想我会这样说,导致你犯了错误的案例..

我已经读过,如果我没有将我的自定义单元格分配到cell.contentview中的cellforRowAtIndexPath,则可能会出现不显示左手删除标志的情况。我试过了,但得到了一个错误。

这是我第一次使用IB制作的自定义单元格,所以如果我犯了一个愚蠢的错误,请与我同行。

cellForRowAtIndexPath中的代码,我在其中分配自定义单元格:

static NSString *CellIdentifier = @"CustomCell";    
CustomCell *cell = (CustomCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {        
    NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];        
    for (id currentObject in topLevelObjects){
        if ([currentObject isKindOfClass:[UITableViewCell class]]){
            cell =  (CustomCell *) currentObject;
            break;
        }
    }        
}
// some more setup and stuff
return cell;

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

使自定义单元格创建UITableViewCell的子类。制作带有视图的笔尖并连接插座:

@interface CustomCell : UITableViewCell
{
    IBOutlet UIView* _cellView;
}

覆盖initWithStyle:reuseIdentifier:方法并在那里加载nib。将自定义视图添加到单元格的内容视图中:

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self)
    {
        [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];
        [_cellView setFrame:[[self contentView] bounds]];
        [[self contentView] addSubview:_cellView];
    }
    return self;
}

然后在cellForRowAtIndexPath代码中,您只需致电:

if (cell == nil)
{
    cell = [[[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier: CellIdentifier ] autorelease];
}

答案 1 :(得分:0)

由于我的ViewController是UIViewController的子类,而不是UITableViewController,我需要使Edit按钮切换为:

- (IBAction)editButtonPressed:(id)sender {
   if (self.myTableView.isEditing) {
    self.editButton.title = @"Edit";
    self.myTableView.editing = NO;
   }
    else{
        self.editButton.title = @"Done";
        self.myTableView.editing = YES;
    }
}

而不是

- (IBAction)editButtonPressed:(id)sender {
    if (self.myTableView.isEditing) {
        self.editButton.title = @"Edit";
        self.myTableView.editing = NO;     
    }
    else{
        self.editButton.title = @"Done";
        self.myTableView.editing= YES;
    }
}

希望能帮助别人......