开发者

iphone button pressed for 3 seconds goes to a different view

I have a button in my app that when pressed goes to a view but I need that when pressed for 3 seconds it would go to a different view,

like when you are on ipad on safari and you开发者_开发技巧 keep pressed the url, and it shows a pop up with copy etc,

but I need that when pressed for 3 second it goes to another view...

hope this makes sense, I will explain better if not understood,

thank you so much! pd, also how to make it show the pop up style window? cheers!


Try setting an NSTimer property in your view controller. When the button's pressed, create the timer and assign it to your property. You can detect that moment with this:

[button addTarget:self action:@selector(startHoldTimer) forControlEvents:UIControlEventTouchDown];

and assign with this:

-(void) startHoldTimer {
    self.myTimer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(goToNewView:) userInfo:nil repeats:NO];
}

Then set an action to run on a canceled touch, or a touch up inside:

[button addTarget:self action:@selector(touchUp) forControlEvents:UIControlEventTouchUpInside];
[button addTarget:self action:@selector(cancelTimer) forControlEvents:UIControlEventTouchCancel];

and

//if timer fires, this method gets called
-(void) goToNewView {
    [self cancelTimer];
    [self loadSecondView];
}

// normal button press invalidates the timer, and loads the first view
-(void) touchUp {
    [self cancelTimer];
    [self loadFirstView];
}

//protected, just in case self.myTimer wasn't assigned
-(void) cancelTimer {
    if (self.myTimer != nil)
        if ([self.myTimer isValid]) {
            [self.myTimer invalidate];
    }
}

That should take care of it!


Use a UILongPressGestureRecognizer, added to the button with -addGestureRecognizer:—it'll handle timing the touch and fire an event when it recognizes that the button's been held down for a while. You might want to reconsider your interaction pattern, though—generally, things that can be long-pressed aren't buttons, they're actual pieces of data in a view, like an image or a link in Safari.


One possible approach would be to implement one of the touches events (I don't remember the name, but the method that fires when you touch down on the button), and schedule a timer to fire in three seconds. If the user lifts her finger before that time, cancel the timer and perform the normal button click. If the time does fire (i.e. 3 seconds have elapsed), ignore the touch up event and load your new view.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜