0

我有一个非常基本的应用程序,如果“if”语句的条件为真,则在其中实例化第二个 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

第二个屏幕成功加载,但日志消息仍然存在,这意味着 FirstViewController 的方法仍然存在,尽管在 SecondViewController 的视图中。我究竟做错了什么?

4

3 回答 3

1

看看你可以在你- (void)viewWillDisappear:(BOOL)animated- (void)viewDidDisappear:(BOOL)animated第一个视图控制器上实现这些方法来停止/禁用任何活动或触摸检测。

于 2013-07-29T20:05:48.327 回答
1

What you're seeing is the result of the way events are handled in UIKit (check out the "Event Handling Guide for iOS", especially the "Event Delivery: The Responder Chain" section). So what's happening is that since SecondViewController's view doesn't override touchesBegan or touchesEnded, the touch is passed up the responder chain, first to SecondViewController, and then to FirstViewController, which finally does handle those events (FirstViewController is still the window's root view controller after the modal presentation).

Two ways to fix this. You can override touchesBegan and touchesEnded in SecondViewController (or its view I guess), and just have empty methods.

Another way would be to subclass FirstViewController's view, and override the methods there, rather than in the controller. You would still have to do the presentation of SecondViewController from the controller -- you could call a method to do that from the view with [self.nextResponder someMethod].

于 2013-07-30T15:42:32.867 回答
0

SecondViewController 是 FirstViewController 的子类吗?如果是这样,触摸事件将通过继承链升级,直到它们被处理。您可以在 SecondViewController 中覆盖这些方法,让它们什么都不做(或任何您想要的)。

于 2013-07-29T21:10:56.103 回答