Objective-C
在您的viewDidLoad:
方法中写下:
-(void)viewDidLoad {
UIImageView *imageview = [[UIImageView alloc]initWithFrame:CGRectMake(100.0, 100.0, 100.0, 100.0)];
[imageview setImage:[UIImage imageNamed:@"image.png"]];
[imageview setUserInteractionEnabled:YES];
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapping:)];
[singleTap setNumberOfTapsRequired:1];
[imageview addGestureRecognizer:singleTap];
[self.view addSubview:imageview];
}
然后像这样调用你的手势方法:
-(void)singleTapping:(UIGestureRecognizer *)recognizer {
NSLog(@"image clicked");
}
迅速
override func viewDidLoad() {
super.viewDidLoad()
let imageView: UIImageView = UIImageView(frame: CGRect(x: 100.0, y: 100.0, width: 100.0, height: 100.0))
imageView.image = UIImage(named: "image.png")
imageView.isUserInteractionEnabled = true
let singleTap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.singleTapping(recognizer:)))
singleTap.numberOfTapsRequired = 1
imageView.addGestureRecognizer(singleTap)
self.view.addSubview(imageView)
}
@objc func singleTapping(recognizer: UIGestureRecognizer) {
print("image clicked")
}