问题
I created a UIScrollView which contains several UIImageView instances. The SDWebImage framework is used in order to cache images and present them in the UIImageView instances. Now I want to be able to click on these instances of UIImageView.
Previously I added UIButtons to the UIScrollView and added an image to this button. But know I am not able to add a UIImageView to a button. How should I solve this? is it an option to place an UIButton over this view? and how should I do this?
I previously used this to add clickable images (I need to change this, due to the SDWebImage framework, so I cannot use UIImage imageNamed:forState
CGFloat y = i * self.view.frame.size.height/6;
UIButton* aButton = [UIButton buttonWithType:UIButtonTypeCustom];
[aButton setTag:[[idsCol objectAtIndex: i] intValue]];
aButton.frame = CGRectMake(0, y, self.view.frame.size.width/3, self.view.frame.size.height/6);
aButton.imageView.contentMode = UIViewContentModeScaleAspectFit;
[aButton setImage:[UIImage imageNamed:@"image.jpg" forState:UIControlStateNormal];
[aButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
aButton.adjustsImageWhenHighlighted = NO;
[scrollView addSubview:aButton];
I currently need to make the following imageview clickable:
[testImageView setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"]
placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
回答1:
I'm unfamiliar with SDWebImage
, but if this framework would allow you to modify the buttons imageView property directly you'd be better off:
[myButton.imageView setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
Alternatively, if you want to stick with using a image view, you can make it "clickable" by adding a simple tap gesture to it:
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(myMethod:)];
[tap setNumberOfTapsRequired:1];
[tap setNumberOfTouchesRequired:1];
[testImageView setUserInteractionEnabled:YES];
[testImageView addGestureRecognizer:tap];
- (void)myMethod:(UIGestureRecognizer *)sender
{
NSLog(@"%u",sender.view.tag);
}
来源:https://stackoverflow.com/questions/13235600/adding-a-uiimageview-to-uibutton