创建MainViewController继承自UIViewController,创建SubView、MyWindow 继承自UIView
一、在APPDelegate.m中编写代码:
#import "AppDelegate.h"
#import "MyWindow.h"
#import "MainViewController.h"
@interface AppDelegate ()
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[MyWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
[self.window makeKeyAndVisible];
//视图要有一个背景颜色才能被触控响应
[self.window setBackgroundColor:[UIColor redColor]];
[self.window setRootViewController:[[MainViewController alloc] init]];
return YES;
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
NSLog(@"%@ %@", [self class], NSStringFromSelector(_cmd));
}
-(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
NSLog(@"%@ %@", [self class], NSStringFromSelector(_cmd));
}
//触控结束
-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
NSLog(@"%@ %@", [self class], NSStringFromSelector(_cmd));
}
//取消触控
-(void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
NSLog(@"%@ %@", [self class], NSStringFromSelector(_cmd));
}
@end
#import "MainViewController.h"
#import "SubView.h"
@interface MainViewController ()
@end
@implementation MainViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self.view setBackgroundColor:[UIColor lightGrayColor]];
SubView *subView1 = [[SubView alloc] initWithFrame:CGRectMake(20, 50, 100, 100)];
[subView1 setBackgroundColor:[UIColor blackColor]];
[subView1 setViewName:@"Black"];
[self.view addSubview:subView1];
SubView *subView2 = [[SubView alloc] initWithFrame:CGRectMake(200, 200, 100, 100)];
[subView2 setBackgroundColor:[UIColor greenColor]];
[subView2 setViewName:@"Green"];
[self.view addSubview:subView2];
SubView *subView3 = [[SubView alloc] initWithFrame:CGRectMake(0, 0, 50, 150)];
[subView3 setBackgroundColor:[UIColor yellowColor]];
[subView3 setViewName:@"Yellow"];
[self.view addSubview:subView3];
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[super touchesBegan:touches withEvent:event];
NSLog(@"%@ %@", [self class], NSStringFromSelector(_cmd));
}
@end
#import "SubView.h"
@implementation SubView
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[super touchesBegan:touches withEvent:event];
NSLog(@"%@ %@", self.viewName, NSStringFromSelector(_cmd));
}
@end
#import "MyWindow.h"
@implementation MyWindow
-(void)touchesBegan:(NSSet<UITouch *>*)touches withEvent:(UIEvent *)event
{
// [super touchesBegan:touches withEvent:event];
NSLog(@"%@ %@", [self class], NSStringFromSelector(_cmd));
}
@end