setTitle:forState:在dispatch_after()中不起作用

时间:2013-07-19 00:36:32

标签: ios uibutton grand-central-dispatch

所有

我正在努力 i)禁用标题为Count的按钮 ii)将其标题更改为Busy,并在延迟delta秒后更改 iii)启用按钮和 iv)将其标题改回计数

这一切都应该发生在UIButton的行动代码中。

我可以做步骤i)-iii),但步骤iv)不起作用:

[sender setEnabled:NO];  // the button is now disabled, clicking on it has no effect 
[sender setTitle:@"Busy ... " forState:UIControlStateDisabled];


// wait delay seconds before reenabling the count button
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, delta * NSEC_PER_SEC),
               dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),^{
               [self.countBTN setEnabled:YES];
               [self.countBTN setTitle:@"Count" forState:UIControlStateReserved];
               });

// after delta seconds, the button is re-enabled, but its title is still "Busy ..."

对于为什么这不起作用的任何见解都将非常赞赏!

1 个答案:

答案 0 :(得分:4)

您需要在主线程上运行UI代码,而不是后台线程。

变化:

dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)

为:

dispatch_get_main_queue()

编辑:

如果您想更改按钮的主标题,可能还需要将UIControlStateReserved更改为UIControlStateNormal