【发布时间】:2009-05-12 06:59:32
【问题描述】:
如何在UITableViewCell 上添加自定义按钮,然后在不使用界面生成器和自定义单元格的情况下删除带有该按钮的单元格?
【问题讨论】:
标签: iphone cocoa-touch uitableview
如何在UITableViewCell 上添加自定义按钮,然后在不使用界面生成器和自定义单元格的情况下删除带有该按钮的单元格?
【问题讨论】:
标签: iphone cocoa-touch uitableview
如果你真的想在没有子类的情况下添加自定义按钮,只需将按钮添加到单元格的 contentView 中:
[cell.contentView addSubview:customButton];
您可以设置按钮的所有特性:框架、目标、选择器等...广告然后使用上述调用将其添加到单元格中。
UIButton *customButton = [UIButton buttonWithType:UIButtonTypeCustom];
customButton.frame=//whatever
[customButton setImage:anImage forState:UIControlStateNormal];
[customButton setImage:anotherImage forState:UIControlStateHighlighted];
[customButton addTarget:self action:@selector(delete) forControlEvents: UIControlEventTouchUpInside];
//yadda, yadda, .....
你也可以标记它
customButton.tag = 99999;
这样你以后可以找到它:
UIButton *abutton = (UIButton*) [cell.contentView viewWithTag:99999];
您需要决定何时添加按钮,可能是在单元格选择中,可能是在编辑模式中...只需将代码放入您选择的委托方法中即可。
【讨论】:
如果按钮的唯一目的是提供删除,您应该查看UITableViewDataSource,它有一个名为- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath 的方法。像这样实现它:
- (BOOL)tableView:(UITableView *)tableView
canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
然后执行:
- (void)tableView:(UITableView *)tableView
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath
{
// Database removal code goes here...
}
要使用这些方法,请让您的 UITableViewController 通过执行以下操作来实现 UITableViewDataSource 协议:
MyClass : UITableViewController <UITableViewDataSource>
在你的头文件中,一定要记得将viewController的数据源设置为self。
【讨论】: