向UiTableViewCell添加删除按钮

时间:2014-04-07 12:23:37

标签: ios objective-c uitableview

由于我在我的应用程序中使用了滑出菜单控制器 - 在UITablewViewCell上滑动删除不再有效,因为使用平移手势来打开/关闭侧面菜单。

所以,我正在考虑添加一个删除按钮,以便始终显示每个单元格 - 因此用户只需点击删除即可删除单元格。

我将此代码添加到UItableView cellforRowAtIndexPath方法:

    /* Remove Button */
UIButton *removeButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
removeButton.frame = CGRectMake(200.0f, 5.0f, 75.0f, 30.0f);
[removeButton setTitle:@"Remove" forState:UIControlStateNormal];
removeButton.tintColor = [UIColor colorWithRed:0.667 green:0.667 blue:0.667 alpha:1]; /*#aaaaaa*/
removeButton.titleLabel.font = [UIFont systemFontOfSize:15];
[cell addSubview:removeButton];
[removeButton addTarget:self
                 action:@selector(removeItem:)
          forControlEvents:UIControlEventTouchUpInside];

这会添加按钮,在删除方法中,我不确定如何实际删除正确的单元格。

有人能指出我在正确的方向吗?

谢谢!

3 个答案:

答案 0 :(得分:1)

基本上你需要在按下删除时必须删除cell的索引。

您可以设置tag属性,当按下按钮时,您可以检查发送事件的按钮的标签属性。

见下面的代码,

UIButton *removeButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
removeButton.tag = indexPath.row;
removeButton.frame = CGRectMake(200.0f, 5.0f, 75.0f, 30.0f);
[removeButton setTitle:@"Remove" forState:UIControlStateNormal];
removeButton.tintColor = [UIColor colorWithRed:0.667 green:0.667 blue:0.667 alpha:1]; /*#aaaaaa*/
removeButton.titleLabel.font = [UIFont systemFontOfSize:15];
[cell addSubview:removeButton];
[removeButton addTarget:self
                 action:@selector(removeItem:)
          forControlEvents:UIControlEventTouchUpInside];


-(void) removeItem:(id) sender
{
 UIButton *button = (UIButton*)sender;

 int index = button.tag;
}

答案 1 :(得分:0)

试试这个,

- (IBAction)removeItem:(id)sender {
     UIButton *button = (UIButton *)sender;
     CGPoint pointInTable = [button convertPoint:button.bounds.origin toView:_tableView];    
     NSIndexPath *indexPath = [_tableView indexPathForRowAtPoint:pointInTable];
     //Remove the cell at indexPath
}

答案 2 :(得分:0)

// 1。添加标签到按钮,用于识别字母

removeButton.tag = indexPath.row;

// 2。获取单元格

UITableViewCell *cellToBeDeleted = [tableView cellForRowAtIndexPath:sender.tag];
相关问题