隐藏UITableViewCell中的按钮

时间:2013-04-29 19:03:53

标签: ios objective-c uibutton uitableview

我目前有一个包含8行的表格,每行都有一个标签在右侧,一个按钮在左侧。我希望我可以隐藏所有按钮,直到用户按下右上角的“编辑”按钮,然后它们会出现,允许用户与每个表格单元格进行交互。我不知道这是否可行,因为它们位于UITableViewCell中,或者是否有更简单的方法来为每个单元格召唤按钮

更新

好吧所以我放置了所有隐藏的属性,似乎没有错误,但应用程序无法识别任何错误。尽管它们被设置为最初隐藏,但按钮仍保持不被隐藏。这是我的代码

这是我的表格单元格代码:

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

    cell.textLabel.text = @"Free Block";

    UIButton*BlockButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];

    BlockButton.frame = CGRectMake(225.0f, 5.0f, 75.0f, 35.0f);
    [BlockButton setTitle:@"Change" forState:UIControlStateNormal];
    [BlockButton addTarget:self action:@selector(Switch:) forControlEvents:UIControlEventTouchUpInside];

    Blockbutton.backgroundColor = [UIColor colorWithRed:102/255.f
                                                 green:0/255.f
                                                 blue:51/255.f
                                                 alpha:255/255.f];
    Blockbutton.hidden = YES;
    [cell addSubview:BlockButton];
    return cell;
}

这是我的方法代码:

- (IBAction)Editmode:(UIButton *)sender 
{
    Blockbutton.hidden = !Blockbutton.hidden;
    [self.tableView reloadData];
}

关于可能出现什么问题的任何想法或想法?

4 个答案:

答案 0 :(得分:3)

如果您还没有UITableViewCell子类,则需要创建它。在该课程中,覆盖setEditing:animated:,如果新值为YES,则启用/添加/取消隐藏按钮。

- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
    [super setEditing:editing animated:animated];

    if (editing) {
        // add your button
        someButton.hidden = NO;

    } else {
        // remove your button
        someButton.hidden = YES;
    }
}

这是可选的,但如果animatedYES,建议您为更改设置动画。

注意:这假设您已经连接了编辑按钮,更改了UITableView的编辑模式。如果不这样做,请在按钮操作中的setEditing:animated:上致电UITableView。这将自动在每个可见的表格单元格上调用setEditing:animated:

答案 1 :(得分:0)

使用一个BOOL变量来定义是否显示删除按钮,对于btnName.hidden = boolVar使用此BOOL var,最初使boolVar = NO,当用户点击编辑切换bool var并重新加载tableview时。 / p>

答案 2 :(得分:0)

这里的诀窍是要记住,表的单元格由cellForRowAtIndexPath:确定。您可以通过发送表reloadData:来重新调用该方法。

所以,只需保留一个BOOL实例变量/ property。使用按钮切换该实例变量并调用reloadData:。如果在调用cellForRowAtIndexPath:时,实例变量为YES,则将按钮的hidden设置为YES;如果是,否则为NO。

答案 3 :(得分:0)

另一个选择是测试你是否在cellForRowAtIndexPath方法中处于编辑模式。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
     UITableViewCell *cell = //(obtain your cell however you like)
     UIButton *button = cell.button; //(get button from cell using a property, a tag, etc.)
     BOOL isEditing = self.editing //(obtain the state however you like)
     button.hidden = !isEditing;
     return cell;
}

无论何时进入编辑模式,都要重新加载tableView数据。这将使表格视图再次询问单元格,但在这种情况下,按钮将被设置为不隐藏。

- (void)enterEditingMode {
    self.editing = YES;
    [self.tableView reloadData];
}