[英]Add a UITapGestureRecognizer to a subview
I have been searching for hours ... Needless to say, I'm rather new in programming. 我一直在找几个小时...不用说,我在编程方面是相当新的。 My goal is to display a subview programmatically and to remove it by tapping on it.
我的目标是以编程方式显示子视图并通过点击将其删除。
Already working: Displaying the subview and removing it by tapping on the view (code below). 已经工作:显示子视图并通过点击视图(下面的代码)将其删除。
Doesn't work - whatever I try: Removing the subview by tapping exclusively on the subview. 不起作用-无论我如何尝试:通过仅点击子视图来删除子视图。
Thanks for your help! 谢谢你的帮助!
My .h-file: 我的.h文件:
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController {
UIImageView *canvas;
UIImageView *square;
}
@property (nonatomic, strong) UIImageView *canvas;
@property (nonatomic, strong) UIImageView *square;
@property (nonatomic) NSUInteger numberOfTouchesRequired;
- (void)handleSingleTap: (UITapGestureRecognizer *)singleTapGestureRecognizer;
@end
My .m-file: 我的.m文件:
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize canvas;
@synthesize square;
- (void)handleSingleTap: (UITapGestureRecognizer *)singleTapGestureRecognizer {
NSLog(@"tapGesture");
[square removeFromSuperview];
}
- (void)loadView {
canvas = [[UIImageView alloc] initWithFrame: [[UIScreen mainScreen] applicationFrame]];
[canvas setImage:[UIImage imageNamed:@"canvas.png"]];
self.view = canvas;
square = [[UIImageView alloc] initWithFrame:CGRectMake(170, 320, 40, 40)];
[square setImage:[UIImage imageNamed:@"square.png"]];
[self.view setUserInteractionEnabled:YES];
[canvas addSubview:square];
NSLog(@"square");
}
- (void)viewDidLoad {
[super viewDidLoad];
UITapGestureRecognizer *singleTapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
NSLog(@"initialize");
singleTapGestureRecognizer.numberOfTapsRequired = 1;
NSLog(@"number of taps");
[self.view addGestureRecognizer:singleTapGestureRecognizer];
NSLog(@"square gestureRecognizer");
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
Instead of 代替
[self.view addGestureRecognizer:singleTapGestureRecognizer];
you should say 你应该说
[square addGestureRecognizer:singleTapGestureRecognizer];
If you want to remove a subview exclusively, when you tap on that view, then you will need to add tap gesture on that view 如果要专门删除子视图,则在点击该视图时,需要在该视图上添加点击手势
[square addGestureRecognizer:singleTapGestureRecognizer];
rather than 而不是
[self.view addGestureRecognizer:singleTapGestureRecognizer];
Also you will need to setUserInteractionEnabled to YES of UIImage
because UIImage's
setUserInteractionEnabled is default to NO. 你还需要setUserInteractionEnabled到的是
UIImage
,因为UIImage's
setUserInteractionEnabled默认为NO。
[square setUserInteractionEnabled:YES];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.