如何在iOS 8中的子类UIView中调用touchesBegan?

时间:2015-08-08 09:05:05

标签: ios objective-c uiview

我希望在子touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event中调用UIView

AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    [self.window setRootViewController:[[UIViewController alloc] init]];

    CGRect firstFrame = self.window.bounds;
    HypnosisView *firstView = [[SubClassedView alloc] initWithFrame:firstFrame];

    [self.window addSubview:firstView];

    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];

    return YES;
}

SubClassedView.h

#import <UIKit/UIKit.h>

@interface SubClassedView : UIView

@end

SubClassedView.m

#import "SubClassedView.h"

@implementation SubClassedView

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    NSLog(@"Here!");
}

@end

当我触摸屏幕时,控制台没有输出“Here!”正如我想的那样。

我使用最新的Xcode 7 beta 5。

如何以正确的方式调用touchesBegan

非常感谢。

1 个答案:

答案 0 :(得分:2)

您正在添加UIViewController作为窗口的子视图,而不是作为根视图控制器视图的子视图。您的根视图控制器应该是UIViewController 子类,以便您可以修改其行为以构建应用程序的导航流。

子类HypnosisView,并在其视图层次结构中将您的@interface MyViewController : UIViewController @property(nonatomic, strong) HypnosisView *hypnosisView; @end @implementation MyViewController - (void)viewDidLoad { [super viewDidLoad]; self.hypnosisView = [[HypnosisView alloc] initWithFrame:self.view.bounds]; [self.view addSubview:hypnosisView]; } @end 添加为子视图:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    MyViewController *myVC = [[MyViewController alloc] init];
    [self.window setRootViewController:myVC];

    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];

    return YES;
}

然后在您的app委托中,将您的视图控制器子类设置为根视图控制器:

left join

这是一种老式的做事方式。您是否有任何理由不使用故事板来构建界面?