我一直在寻找几个小时......不用说,我在编程方面比较新。 我的目标是以编程方式显示子视图,并通过点击它来删除它。
已经工作:通过点击视图(下面的代码)显示子视图并将其删除。
不起作用 - 无论我尝试什么:只通过点击子视图来删除子视图。
感谢您的帮助!
我的.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
我的.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
答案 0 :(得分:0)
而不是
[self.view addGestureRecognizer:singleTapGestureRecognizer];
你应该说
[square addGestureRecognizer:singleTapGestureRecognizer];
答案 1 :(得分:0)
如果您想要专门删除子视图,当您点按该视图时,则需要在该视图上添加点按手势
[square addGestureRecognizer:singleTapGestureRecognizer];
而不是
[self.view addGestureRecognizer:singleTapGestureRecognizer];
此外,您需要将setUserInteractionEnabled设置为UIImage
的YES,因为UIImage's
setUserInteractionEnabled默认为NO。
[square setUserInteractionEnabled:YES];