我还没有找到一个非常简单的方法来实现这个。我看到的方法都需要使用定时器等东西。是否有一种简单的方法,我可以按住UIButton并重复执行该操作直到放手为止?
我还没有找到一个非常简单的方法来实现这个。我看到的方法都需要使用定时器等东西。是否有一种简单的方法,我可以按住UIButton并重复执行该操作直到放手为止?
//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;
现在在你的实现文件(.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];
}
-(IBAction)theTouchDown {
g = true;
}
-(IBAction)theTouchUpInside {
g = false;
}
-(IBAction)theTouchUpOutside {
g = false;
}
然后在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.
}
}
不幸的是,看起来你仍然需要自己编写这个功能。 最简单的方式(你仍然需要一个计时器):
执行你想重复的动作的函数:
-(void) actionToRepeat:(NSTimer *)timer
{
NSLog(@"Action triggered");
}
在您的.h文件中声明并设置定时器属性:
@interface ClassFoo
{
NSTimer* holdTimer;
}
然后在.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;
}
然后只需在 IB 中从按钮链接到 Touch Down
事件到 startAction
,并将 Touch Up Inside
链接到“Stop Action”。这不是一个一行代码的解决方案,但它允许您自定义操作重复的速率,并允许您从另一个 outlet/action 触发它。
如果您经常使用此功能,则可以考虑子类化 UIButton
并添加此功能-这样,第一次实现时只需要(稍微)费点功夫。
TouchAndHoldButton * pageDownButton = [TouchAndHoldButton buttonWithType:UIButtonTypeCustom];
[pageDownButton addTarget:self action:@selector(pageDownAction:) forTouchAndHoldControlEventWithTimeInterval:0.2];
祝你好运!
我无法回复第一个,但是这一行:
timer = [NSTimer scheduledTimerWithInterval: 1.0 target:self selector:@selector(targetMethod:) userInfo:nil repeats: YES];
至少需要支持iOS 4.1或更高版本:
timer = [NSTimer scheduledTimerWithTimeInterval: 1.0 target:self selector:@selector(targetMethod:) userInfo:nil repeats: YES];
我知道这是一个老问题,但作为一种简单的方法,可以考虑使用“[NSObject performSelector:withObject:afterDelay:]”在任何特定时间间隔内重复调用方法。
在这种情况下:
NSTimeInterval someTimeInterval = 1;
- (IBAction)action:(id)sender {
UIButton * const button = sender;
if (button.state != UIControlStateHighlighted) {
return;
}
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:_cmd object:sender];
[self performSelector:_cmd withObject:sender afterDelay:someTimeInterval];
}