how to change tableView Cell button on click in iphone
我有带有自定义单元格的表格视图,它具有按钮,我希望当用户单击该按钮时,该按钮的图像应更改任何想法,因为我希望通过另一种方法更改cellImage按钮图像。
1 2 | [cell.theSyncButton addTarget:self action:@selector(syncButtonAction:) forControlEvents:UIControlEventTouchUpInside]; [cell.theSyncButton setTag:indexPath.row]; |
方法:
1 2 3 | -(IBAction)syncButtonAction:(id)sender{ // I want to change the cell.SyncButton image here } |
任何想法如何做到。
1 2 3 4 | -(IBAction)syncButtonAction:(id)sender{ UIButton *btn = (UIButton *)sender; [btn setImage:img forState:UIControlStateSelected]; } |
1 2 | [btnSync setImage:[UIImage imageNamed:@"refresh.png"] forState:UIControlStateNormal]; [btnSync setImage:[UIImage imageNamed:@"refresh-active.png"] forState:UIControlStateHighlighted]; |
1 2 3 4 | -(IBAction)syncButtonAction:(id)sender{ [button setImage:[UIImage imageNamed:@"yourimage.png"] forState:UIControlStateNormal]; } |
这是我的解决方案:
我使用UIImageVIew作为按钮
例如,starIcon是一个UIImageView,我将其添加到我的自定义UITableViewCell中作为按钮。
而ArticleCell是我的自定义UITableViewCell类。
在UITableView dataSource方法cellForRowAtIndexPath中的
:
1 2 3 4 5 6 7 8 9 10 11 | ArticleCell* cell = [tableView dequeueReusableCellWithIdentifier:@"reused"]; if (cell==nil) { NSLog(@"init tableViewCell"); cell = [[ArticleCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"reused"]; UITapGestureRecognizer* gesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(buttonCallback:)]; gesture.numberOfTapsRequired=1; gesture.numberOfTouchesRequired=1; [cell.starIcon addGestureRecognizer:gesture]; cell.starIcon.userInteractionEnabled=YES; NSLog(@"init tableViewCell end"); } |
确保将userInteractionEnabled设置为== true;
然后,在您的buttonCallback方法中,您可以通过
获得UIimageView
1 2 3 | -(void)buttonCallback:(UIGestureRecognizer*)gestureRecognizer{ UIImageView* star = (UIImageView*)[gestureRecognizer view]; } |
因此,您可以更改imageView。
除了要做的所有代码以外,您还要做的是:
1 2 | UIImage *img = [UIImage imageNamed:@"yourImage.png"]; [cell.theSyncButton setImage:img forState:UIControlStateSelected]; |
尝试一下..
1 2 3 4 5 6 7 8 | -(IBAction)syncButtonAction:(id)sender { UIButton * syncButton = (UIButton *) sender; [syncButton setBackgroundImage: <NormalImage.png> forState: UIControlStateNormal]; [syncButton setBackgroundImage: <HighlightedImage.png forState: UIControlStateHighlighted]; } |