我有一个非常基本的应用程序,如果"if"语句的条件为true,则会实例化第二个ViewController。加载第二个ViewController后,第一个ViewController的方法仍在运行。我需要停止以前的所有方法,以便应用程序正确运行。
//在FirstViewController.h 中
#import <UIKit/UIKit.h>
@interface FirstViewController : UIViewController
{
NSTimeInterval beginTouchTime;
NSTimeInterval endTouchTime;
NSTimeInterval touchTimeInterval;
}
@property (nonatomic, readonly) NSTimeInterval touchTimeInterval;
- (void) testMethod;
@end
//在FirstViewController.m 中
#import "FirstViewController.h"
#import "SecondViewController.h"
@implementation FirstViewController
@synthesize touchTimeInterval;
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (void) testMethod
{
if (touchTimeInterval >= 3)
{
NSLog(@"Go to VC2");
SecondViewController *secondBViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"SecondViewController"];
[self presentViewController:secondViewController animated:YES completion:nil];
}
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
beginTouchTime = [event timestamp];
NSLog(@"Touch began");
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
endTouchTime = [event timestamp];
NSLog(@"Touch ended");
touchTimeInterval = endTouchTime - beginTouchTime;
NSLog(@"Time interval: %f", touchTimeInterval);
[self testMethod]; // EDIT: USED TO BE IN viewDidLoad
}
@end
第二个屏幕成功加载,但日志消息仍然存在,这意味着尽管在SecondViewController的视图中,FirstViewController的方法仍然存在。我做错了什么?
您看到的是UIKit中事件处理方式的结果(请参阅"iOS事件处理指南",尤其是"事件交付:响应程序链"部分)。因此,由于SecondViewController的视图不会覆盖touchesBegan或touchesEnded,因此触摸会沿着响应器链向上传递,首先传递给SecondViewController,然后传递给FirstViewController,后者最终会处理这些事件(在模式演示后,FirstViewControl仍然是窗口的根视图控制器)。
有两种方法可以解决这个问题。您可以在SecondViewController(或者我想是它的视图)中覆盖touchesBegan和touchesEnded,并且只有空方法。
另一种方法是将FirstViewController的视图子类化,并覆盖那里的方法,而不是在控制器中。您仍然需要从控制器中演示SecondViewController——您可以使用[self.nextResponder someMethod]从视图中调用一个方法来实现这一点。
查看- (void)viewWillDisappear:(BOOL)animated
和- (void)viewDidDisappear:(BOOL)animated
您可以在第一个视图控制器上实现这些方法,以停止/禁用任何活动或触摸检测。
SecondViewController是FirstViewController的子类吗?如果是这样,触摸事件将通过继承链升级,直到它们得到处理。您可以在SecondViewController中重写这些方法,并让它们不执行任何操作(或其他任何您想要的操作)。