检测在UITableview中单击了哪个按钮并更改按钮图像

时间:2013-01-18 09:49:50

标签: iphone ios objective-c

我在视图中使用了三个表,并使用标记将它们相互隔离。在我的第二个表视图中,我制作了一个cutom uitableview并在其中添加了标签和按钮。

这是我在cellforrowatindexpath

中写的按钮
followingButton = [UIButton buttonWithType:UIButtonTypeCustom];

  [followingButton addTarget:self action:@selector(followingButtonpressed:)forControlEvents:UIControlEventTouchUpInside];

 [followingButton setImage:[UIImage imageNamed:@"following12.png"] forState:UIControlStateNormal];

following.tag=indexpath.row;

 [followingButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

followingButton.frame = CGRectMake(220.0 ,20.0, 100, 40.0);

 [cell.contentView addSubview:followingButton];

==

-(void)followingButtonpressed:(id)sender
{

 UIView *contentView1 = (UIView *)[sender superview];

 UITableViewCell *cell1= (UITableViewCell *)[contentView1 superview];

 NSIndexPath *indexPath1 = [followingTable indexPathForCell:cell1];

[sender tag];

NSLog(@"sender tag --%d",[sender tag]);

 // UIButton *button = (UIButton *)sender;

 // UITableViewCell *cell = (UITableViewCell*)[button superview];

  UIButton *tempButtom = (UIButton *)[cell1 viewWithTag:[sender tag]];

  [tempButtom setImage:[UIImage imageNamed:@"following_off12.png"] 

forState:UIControlStateNormal];

}

但它的崩溃和我无法更改所选按钮的图像,请帮助

2 个答案:

答案 0 :(得分:0)

Use this to detect which button has been pressed

    UIView *senderButton = (UIView*) sender;
    NSIndexPath *indexPath = [(UITableView *)self.superview indexPathForCell: (UITableViewCell*)[[senderButton superview]superview]];

答案 1 :(得分:0)

为每个Tag提供UIButton并编写以下代码以检测按下哪个按钮

 - (void)buttonPressedAction:(id)sender
{
   UIButton *button = (UIButton *)sender;
   // Get the UITableViewCell which is the superview of the UITableViewCellContentView which is the superview of the UIButton
   (UITableViewCell*)cell = [[button superview] superview];
   int row = [myTable indexPathForCell:cell].row;

  // Here **row** give you tad of specific UIButton that you tapped

  if (row == yourTag )
  {
     // write code for action
  }
}

或者您可以每次为单元格设置标记,但不能为UIButton设置标记。那么你的行动将是:

- (void)buttonPressedAction:(id)sender
{ 
   UIButton *button = (UIButton *)sender;
   int row = [button superview].tag;

   // Here **row** give you tad of specific UIButton that you tapped

  if (row == yourTag )
  {
     // write code for action
  }

}