Joh*_*n S 9 iphone objective-c uibutton uitableview ios
我一直在寻找解决方案,但似乎找不到适合我的解决方案.我有一个内置按钮的自定义单元格.我的问题是如何将indexPath传递给action方法?
现在我正在做
[cell.showRewards addTarget:self action:@selector(myAction:) forControlEvents:UIControlEventTouchUpInside];
Run Code Online (Sandbox Code Playgroud)
在我的cellForRowAtIndexPath方法中,我的方法是:
-(IBAction)myAction:(id)sender{
NSIndexPath *indexPath = [self.tableView indexPathForCell:(MyCustomCell *)[sender superview]];
NSLog(@"Selected row is: %d",indexPath.row);
}
Run Code Online (Sandbox Code Playgroud)
有小费吗?谢谢.
cell.showRewards.tag = indexPath.row;
Run Code Online (Sandbox Code Playgroud)
-(IBAction)myAction:(id)sender
{
UIButton *btn = (UIButton *)sender;
int indexrow = btn.tag;
NSLog(@"Selected row is: %d",indexrow);
}
Run Code Online (Sandbox Code Playgroud)
只想添加我认为最好的解决方案:UIView上的一个类别.
这很简单:
- (void)somethingHappened:(id)sender
{
NSIndexPath *indexPath = [self.tableView indexPathForCell:[sender parentCell]];
// Your code here...
}
Run Code Online (Sandbox Code Playgroud)
只需在UIView上使用此类别:
@interface UIView (ParentCell)
- (UITableViewCell *)parentCell;
@end
@implementation UIView (ParentCell)
- (UITableViewCell *)parentCell
{
UIView *superview = self.superview;
while( superview != nil ) {
if( [superview isKindOfClass:[UITableViewCell class]] )
return (UITableViewCell *)superview;
superview = superview.superview;
}
return nil;
}
@end
Run Code Online (Sandbox Code Playgroud)
虽然我觉得设置tag按钮是一种方法.您可能需要编写代码以确保每次重用单元格时,都会在按钮对象上更新相应的标记.
相反,我觉得这可行.试试这个 -
-(IBAction)myAction:(id)sender
{
CGPoint location = [sender locationInView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
UITableViewCell *swipeCell = [self.tableView cellForRowAtIndexPath:indexPath];
NSLog(@"Selected row: %d", indexPath.row);
//......
}
Run Code Online (Sandbox Code Playgroud)
基本上你正在做的是获取点击发生的位置的坐标tableView.获取坐标后,tableView可以使用该方法为您提供indexPath indexPathForRowAtPoint:.你很高兴去追寻......
瞧,你不仅仅是indexPath点击发生的实际单元格.要从数据源获取实际数据(假设其NSArray),您可以 -
[datasource objectAtIndex:[indexPath row]];
| 归档时间: |
|
| 查看次数: |
19088 次 |
| 最近记录: |