UIButton,如何防止双重动作发生

时间:2010-07-12 02:56:26

标签: iphone uibutton

我不太确定UIButton是如何工作的。例如,如果我有一个计时器在我按下开始按钮时熄灭,我该怎么做才能使按钮再次按下时,它不会启动另一个计时器。因此我的计时器速度提高了两倍。如果按下按钮两次并启动一个新的计时器,我似乎想要使我的原始计时器无效,但我不知道如何判断该按钮是否被按下两次。

此外,是否有一种方法可以在UIButton按下一次后更改UIButton上的标签,然后在再次按下时将其恢复原状?喜欢,播放/暂停?感谢。

2 个答案:

答案 0 :(得分:0)

如果你的计时器不是零,有人已经设置了它,这意味着按钮已被按下。考虑:

@interface MyController : UIViewController {
    @private NSTimer *timer;
}
- (IBAction)pressButton: (id)sender;
@end

@implementation MyController
- (IBAction)pressButton: (id)sender {
    if (!self->timer) {
        self->timer = [NSTimer scheduledTimer...];
    }
}
@end

答案 1 :(得分:0)

封装和状态管理对于这种情况非常有用。根据你想要封装多少,你可能会考虑让UIButton修改一个新对象(你提到Play / Pause所以我想象某种媒体播放器?)

(在此示例中,您可能会考虑enumeration个状态,以使其更具扩展性,但为了简单起见,我将使用BOOL

@interface MediaManager : NSObject
{

    BOOL isPlaying;  // whether
    NSTimer *playTimer; // timer used exclusively by the media manager
    //... other vars relating to type of media/selected track etc   anything related
}

-(void) togglePlay;


@property (nonatomic, synthesize) NSTimer *playTimer;
@propety (nonatomic, assign) BOOL isPlaying;

@end


@implementation MediaManager

@synthesize playTier, isPlaying;


- (void)togglePlay 
{
    if (!self.isPlaying)  
    {
        if (self.playTimer == nil) // if it hasn't already been assigned
        {
            self.playTimer = [NSTimer ...]; // create and schedule the timer
            self.isPlaying = YES;
        }
    }
    else 
    {
        if (self.playTimer != nil)
        {
            // get the timer and invalidate it
            self.isPlaying = NO;
        }
    }

}

@end

这不是最好的示例,但是通过将状态封装在单独的对象中,您的视图UIButton可以完全依赖于模型状态来呈现自身(假设它包含对已初始化的{{}的引用1}}:

Media Manager

这样,每次要使用此功能时都不必包含状态处理,并且该按钮始终反映其正在操作的对象的真实状态。

您可以更进一步,并将状态字符串封装在对象中,可以以类似的方式查询。

(对于代码写得不好的道歉,我还没喝咖啡)

相关问题