【发布时间】:2011-09-02 20:18:07
【问题描述】:
我正在使用 XCode 的基于导航的应用程序模板来创建一个以 UITableView 为中心的应用程序。
当用户在 UITableView 中选择一行时,我想在该选定单元格内显示一个按钮。我只想在选定的单元格中显示此按钮,而不是在任何其他单元格中。如果用户之后选择不同的单元格,情况也是如此。
我该怎么做呢?有可能吗?
【问题讨论】:
标签: iphone uitableview button row cell
我正在使用 XCode 的基于导航的应用程序模板来创建一个以 UITableView 为中心的应用程序。
当用户在 UITableView 中选择一行时,我想在该选定单元格内显示一个按钮。我只想在选定的单元格中显示此按钮,而不是在任何其他单元格中。如果用户之后选择不同的单元格,情况也是如此。
我该怎么做呢?有可能吗?
【问题讨论】:
标签: iphone uitableview button row cell
子类 UITableViewCell 并向其添加按钮。
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
button = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
[button setFrame:CGRectMake(320.0 - 90.0, 6.0, 80.0, 30.0)];
[button setTitle:@"Done" forState:UIControlStateNormal];
button.hidden = YES;
[self.contentView addSubview:button];
}
return self;
}
然后像这样覆盖 setSelected:
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
self.button.hidden = !selected;
}
【讨论】:
这应该可以使用以下内容:
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
if (lastClickedCell != nil) {
// need to remove button from contentView;
NSArray *subviews = lastClickedCell.contentView.subviews;
for (UIButton *button in subviews) {
[button removeFromSuperview];
}
}
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
// this gives you a reference to the cell you wish to change;
UIButton *cellButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; // you can change the type to whatever you want
[cellButton setFrame:CGRectMake(x, y, w, h)]; // you will need to set the x,y,w,h values to what you want
// if you want the button to do something, you will need the next line;
[cellButton addTarget:self action:@selector(someMethod) forControlEvents:UIControlEventTouchUpInside];
// now you will need to place the button in your cell;
[cell.contentView addSubview:cellButton];
[tableView reloadData]; // this updates the table view so it shows the button;
lastClickedCell = cell; // keeps track of the cell to remove the button later;
}
编辑:当您选择一个新单元格时,您当然需要从 contentView 中删除按钮,因此您需要一些逻辑。子类化可能是一个更简单的解决方案,但如果您不想子类化,这是您需要采取的方法。例如,您可能希望在标题中声明以下内容。
UITableViewCell *lastClickedCell;
然后你会想把它合并到上面(我会改变把它放进去);
【讨论】:
您是否查看 developer.apple.com 以获取 UITableViewController 和 UIButton 的文档?
【讨论】:
这是一个简单的解决方案!
在 viewDidLoad 函数之类的地方创建按钮(确保在 .h 文件中声明它,以便您可以从任何地方引用它)
在 -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
添加以下内容:
if (yourButton)
[yourButton removeFromSuperview];
[[tableView cellForRowAtIndexPath:indexPath] addSubview:yourButton];
[yourButton setSelected:NO];
[yourButton setHighlighted:NO];
【讨论】: