【发布时间】:2016-06-01 08:25:05
【问题描述】:
我正在处理一个要求执行以下步骤的项目。
- 显示初始计数为 0 的
UIButton - 第一次触摸
UIButton会增加计数 - 第二次触摸
UIButton,计数每1秒递增一次
我的代码卡在第 3 步,如果我第二次触摸 UIButton,计数将继续递增 1。我永远无法进入 [self performSelector:@selector(doDelay:) withObject:button afterDelay:1.0]。
如何添加一个计数器来计算用户点击了多少次UIButton?
这是我的代码:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
CGRect rect=[[UIScreen mainScreen] bounds];
UIButton *button=[[UIButton alloc] initWithFrame:rect];
button.backgroundColor=[UIColor redColor];
//Step (1)
[button setTitle:@"Count = 0" forState:UIControlStateNormal];
[self.window addSubview:button];
//Step (2)
[button addTarget:self action:@selector(doButton:) forControlEvents:UIControlEventTouchUpInside];
//Step (3)
[self performSelector:@selector(doDelay:) withObject:button afterDelay:1.0];
return YES;
}
-(void)doButton:(id)sender
{
static int count;
count++;
NSString *s = [NSString stringWithFormat:@"Count = %i", count];
UIButton *b = sender;
[b setTitle:s forState:UIControlStateNormal];
}
-(void)doDelay:(id)object
{
[self doButton:object];
[self performSelector:@selector(doDelay:) withObject:object afterDelay:1.0];
}
【问题讨论】:
-
你不能有多个
action目标;您需要有一种目标方法并根据按钮数在其中执行不同的操作。此外,将按钮直接添加到窗口并在应用程序委托中处理事件是非常不寻常的。您通常会使用 UIViewController 子类。如果您在创建新项目时选择“单一视图应用程序”,XCode 将为您设置所有这些。 -
为什么不能使用 NSTimer 而不是 performSelector:withObject:afterDelay:
-
您的要求是多动作.....?或第 3 步。第二次触摸 UIButton 时每 1 秒增加一次计数.....您再次说“计数将继续增加 1。我永远无法进入 [self performSelector:@selector(doDelay:) withObject :button afterDelay:1.0]."
标签: ios objective-c iphone uibutton