[英]How to change Image of UIImageView in Tableview when it is clicked
I have a Table view that I fill dynamically. 我有一个动态填充的表格视图。 The code for my cellForRowAtIndexPath
method is : 我的cellForRowAtIndexPath
方法的代码是:
- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath {
UIImage * ImageFavorited = [UIImage imageNamed:@"Favorited"];
UIImageView *ImageViewFavorited = (UIImageView *)[cell viewWithTag:7];
ImageViewFavorited.image =ImageFavorited;
ImageViewFavorited.userInteractionEnabled = YES;
NSString *uiid = [[collectionFromData valueForKey:@"id"] objectAtIndex:(indexPath.row)];
MYTapGestureRecognizer *tapped = [[MYTapGestureRecognizer alloc] initWithTarget:self action:@selector(myFunction:) ];
tapped.data = uiid;
tapped.numberOfTapsRequired = 1;
[ImageViewFavorited addGestureRecognizer:tapped];
}
I know, I know, The MYTapGestureRecognizer
is looking odd, I actually extended UITapGestureRecognizer
so I can pass data with it. 我知道,我知道, MYTapGestureRecognizer
看起来很奇怪,我实际上扩展了UITapGestureRecognizer
以便可以通过它传递数据。 (Thank you StackOverFlow Users) , So my problem now is that I want to change the image of my clicked UIImageview after the user click on it. (谢谢StackOverFlow用户),所以我现在的问题是我想在用户单击UIImageview后更改它的图像。 For now I detect the click in the myfunction
function but I can't seem to find a way to change the image. 目前,我在myfunction
函数中检测到单击,但是似乎找不到改变图像的方法。
The code for myfunction
is : myfunction
的代码是:
-(void)myFunction :(id) sender
{
MYTapGestureRecognizer *tap = (MYTapGestureRecognizer *)sender;
NSLog(@"data is = %@", tap.data);
}
Add the following to the myFunction to get the sender view: 将以下内容添加到myFunction中以获取发送者视图:
[(UIGestureRecognizer *)sender view]
Then with that you can change that views properties, since in your case it's a UIImageView, just cast it as a UIImageView and change the image property. 然后,您可以更改该视图的属性,因为在您的情况下为UIImageView,只需将其转换为UIImageView并更改image属性即可。
The completed solution would be: 完成的解决方案将是:
[(UIImageView*) [(UIGestureRecognizer *)sender view]] setImage:[UIImage imageNamed:”blah”]]
Best practice for this situation. 这种情况的最佳实践。
Instead of UIImage
use UIButton
and bind action in your viewController
. 代替UIImage
使用UIButton
并在viewController
绑定操作。 Set the button image of default
and Selected
state storyboard or by code as per what you do. 根据您的操作设置default
和Selected
状态情节提要的按钮图像或代码。
In buttonAction
在buttonAction
sender.selected = !sender.selected;
tableView.raeloadData();
Thats All. 就这样。 If still facing issue then let me knoe. 如果仍然面临问题,那就让我知道。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.