UIButton触摸并保持

Mat*_* S. 14 cocoa-touch uibutton

我没有找到一个非常简单的方法来做到这一点.我所看到的方式需要所有这些计时器和东西.有没有简单的方法我可以持有UIButton并使其一遍又一遍地重复动作直到它被释放?

小智 17

您可以执行以下操作:创建一个NSTimer,它将在应用程序启动时或在viewDidLoad中启动,并且还会生成一个布尔值.

例如:

//Declare the timer, boolean and the needed IBActions in interface.
@interface className {
NSTimer * timer;
bool g;
}
-(IBAction)theTouchDown(id)sender;
-(IBAction)theTouchUpInside(id)sender;
-(IBAction)theTouchUpOutside(id)sender;

//Give the timer properties.
@property (nonatomic, retain) NSTimer * timer;
Run Code Online (Sandbox Code Playgroud)

现在在您的实现文件(.m)中:

//Synthesize the timer
@synthesize timer;
//When your view loads initialize the timer and boolean.
-(void)viewDidLoad {
    g = false;
    timer = [NSTimer scheduledTimerWithInterval: 1.0 target:self selector:@selector(targetMethod:) userInfo:nil repeats: YES];
}
Run Code Online (Sandbox Code Playgroud)

现在为"触摸向下"做一个IBAction设置布尔值让我们说真的.然后为"Touch Up Inside"和"Touch Up Outside"创建另一个IBAction按钮,将布尔值指定为false.

例如:

-(IBAction)theTouchDown {
    g = true;
}

-(IBAction)theTouchUpInside {
    g = false;
}

-(IBAction)theTouchUpOutside {
    g = false;
}
Run Code Online (Sandbox Code Playgroud)

然后在该NSTimer方法中,输入以下内容:(假设g是您声明的布尔值)

-(void) targetmethod:(id)sender {
    if (g == true) {
        //This is for "Touch and Hold"
    }
    else {
        //This is for the person is off the button.
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望这简化了一切......我知道它仍然使用计时器,但没有其他办法.


dav*_*ryn 10

不幸的是,它仍然看起来你必须为自己编写这个功能.最简单的方法(你仍然需要一个计时器):

执行要重复的操作的函数:

-(void) actionToRepeat:(NSTimer *)timer
{
    NSLog(@"Action triggered");
}
Run Code Online (Sandbox Code Playgroud)

在.h文件中声明并设置定时器的属性:

@interface ClassFoo
{
    NSTimer* holdTimer;
}
Run Code Online (Sandbox Code Playgroud)

然后在.m中制作两个IBActions:

-(IBAction) startAction: (id)sender
{
    holdTimer = [NSTimer scheduledTimerWithTimeInterval:0.4 target:self selector:@selector(actionToRepeat:) userInfo:nil repeats:YES];
    [holdTimer retain];
}

-(IBAction) stopAction: (id)sender
{
    [holdTimer invalidate];
    [holdTimer release];
    holdTimer = nil;
}
Run Code Online (Sandbox Code Playgroud)

然后,只需链接到Touch Down从按钮到事件IB startActionTouch Up Inside到"停止行动".它不是一个单行,但它允许您自定义动作重复的速率,并允许您从另一个插座/动作触发它.

UIButton如果您要经常使用此功能,您可以考虑子类化并添加此功能 - 然后第一次实施它只会(稍微)痛苦.


ing*_*ham 9

另一种使用此NBTouchAndHoldButton的方法.这正是您想要的,并且非常容易实现它:

TouchAndHoldButton * pageDownButton = [TouchAndHoldButton buttonWithType:UIButtonTypeCustom];
[pageDownButton addTarget:self action:@selector(pageDownAction:) forTouchAndHoldControlEventWithTimeInterval:0.2];
Run Code Online (Sandbox Code Playgroud)

祝好运!