当UITableViewCell被选中/被点击时,我想调用一个方法。我可以很容易地使用静态表视图来完成这个任务,但是它需要一个对我不好的UITableViewController,因此我使用的是一个普通的vc。
我有10种具体的方法如下:
- (void) methodOne {
NSLog(@"Do something");
}
- (void) methodTwo {
NSLog(@"Do something");
}
....我想在第一个小区被窃听时调用methodOne,在第二个小区被窃听时调用methodTwo等等。
作为第一步,我将numberOfRowsInSection设置为返回10个单元,但不知道如何将选定的单元格与方法连接。有什么快捷的方法吗?创建10个自定义单元格并手动设置自定义单元格的每个方法将是一个很脏的解决方案,而且它没有空闲的位置。
发布于 2014-08-17 18:31:25
您可以在表视图上任何单元格被点击时使用此方法。
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSInteger selectedRow = indexPath.row; //this is the number row that was selected
switch (selectedRow)
{
case 0:
[self methodOne];
break;
default:
break;
}
}使用selectedRow标识选择了哪个行号。如果选择了第一行,则selectedRow将是0。
不要忘记将表视图的委托设置为视图控制器。视图控制器还必须符合UITableViewDelegate协议。
@interface YourViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>只要表视图有数据源和委托,那么它在哪种视图控制器上并不重要。UITableViewController实际上是一个已经有表视图的UIViewController,也是表视图的委托和数据源。
发布于 2017-07-02 13:41:14
您可以创建一个具有方法名称的NSString数组,并按照从对应的UITableViewCell中调用它们的顺序进行。
NSArray *selStringsArr = @[@"firstMethod", @"secondMethod", @"thirdMethod];然后从字符串数组在selector中创建一个tableView:didSelectRowAtIndexPath:,并使用performSelector:调用它。
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *selString = selStringsArr[indexPath.row];
SEL selector = NSSelectorFromString(selString);
if ([self respondsToSelector:@selector(selector)]) {
[self performSelector:@selector(selector)];
}
}当然,使用performSelector:有一些限制,您可以使用read here。
https://stackoverflow.com/questions/25352319
复制相似问题