向select器传递一个参数
我有我的自定义单元格内的UIButton,我想触发一个动作,当用户按下该button,但我需要知道从哪个行UIButton被按下。
这是我的代码:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"]; [self configureCell:cell atIndexPath:indexPath]; return cell; ... [button addTarget:self action:@selector(buttonPressedAction:)forControlEvents:UIControlEventTouchUpInside]; } - (void)buttonPressedAction:(UIButton *)button { //int row = indexPath.row; //NSLog(@"ROW: %i",row); }
我如何将indexPath作为parameter passing给我的select器?
您可以将button的标签属性设置为行号:
button.tag = indexPath.row;
并检索它使用
NSInteger row = button.tag;
或者将索引path对象本身设置为button的关联对象:
objc_setAssociatedObject(button, "IndexPath", indexPath);
和
NSIndexPath *ip = objc_getAssociatedObject(button, "IndexPath");
在添加自定义单元格的button时,可以添加UIButton的tag
属性
UIButton *sampleButton = [[UIButton alloc] init]; sampleButton.tag = indexPath.row;
然后当你打电话,你可以检查标签
- (void)buttonPressedAction:(UIButton*)sender { if(sender.tag==0) { //perform action } }
希望能帮助到你。 快乐编码:)
它甚至比设置标签简单。 尝试这个..
要获取indexPath,请尝试下面的代码。
UIView *contentView = (UIVIew *)[button superview]; UITableViewCell *cell = (UITableViewCell *)[contentView superview]; NSIndexPath *indexPath = [self.tableview indexPathForCell:cell];
要么
NSIndexPath *indexPath = [self.tableview indexPathForCell:(UITableViewCell *)[(UIVIew *)[button superview] superview]];
简单的设置button标签
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"]; [self configureCell:cell atIndexPath:indexPath]; return cell; ... [button setTag = indexPath.row]; // Set button tag [button addTarget:self action:@selector(buttonPressedAction:) forControlEvents:UIControlEventTouchUpInside]; } - (void)buttonPressedAction:(id)sender { UIButton *button = (UIButton *)sender; int row = [button superview].tag; } }