【问题标题】:UIbutton don't change background inside IBActionUIbutton不改变IBAction内的背景
【发布时间】:2013-08-02 12:08:44
【问题描述】:

我有 3 个带有文本的自定义 UIButton,当用户单击其中一个按钮时,我会检查答案是否正确。如果正确,我想将按钮背景设置为绿色,如果不是红色。然后我想在稍微延迟后自动显示下一个问题(他需要一点时间来看看之前的答案是否正确)。

问题是 UIbutton 背景在 IBAction 内部没有改变,但它在 setWordAndAnswers 函数内部改变。而且我不知道为什么会发生(((

代码如下:

-(void)setWordAndAnswers{
if([[currentCollection allWards] count]>0){
    int randCard =arc4random_uniform([[currentCollection allWards] count]-1);
    currentWord=[[currentCollection allWards]objectAtIndex:randCard];
    tvMainWord.text=[currentWord originalWord];

    int wrightAnser =arc4random_uniform(2);
    for(int i=0;i[answers count];i++){
        [[answers objectAtIndex:i]setBackgroundColor:[UIColor whiteColor]];

        if(i==wrightAnser){
            [[answers objectAtIndex:i] 
            setTitle:[currentWord wordTranslate] forState:UIControlStateNormal];
        }
        else{
             [[answers objectAtIndex:i] 
             setTitle:[self getRandomAnswer] forState:UIControlStateNormal];
        }
    }
}

}

- (IBAction)onClickCheckAnswer:(id)sender {
if(!isGameRunning)
    return;
UIButton *button = (UIButton *)sender;
if([[sender title]isEqual:[currentWord wordTranslate]]){
    [button setBackgroundColor:[UIColor greenColor]];
}
else{
    [button setBackgroundColor:[UIColor redColor]];
}
[button setNeedsDisplay];
[NSThread sleepForTimeInterval:0.3f];
[self setWordAndAnswers];

}

【问题讨论】:

    标签: iphone objective-c uibutton ibaction


    【解决方案1】:

    确保 UIButton 是这样的自定义类型:

    UIButton *myButton = [UIButton buttonWithType: UIButtonTypeCustom];
    

    另外你为什么要调用NSThread sleep?,如果你想延迟执行 setwordandanswers 我会使用performSelector:afterDelay,或者如果你有依赖然后使用NSOperationQueue addDependecy

    希望对您有所帮助。

    【讨论】:

    • 非常感谢!!!问题出在 NSThread 睡眠中,我使用了 performSelector:afterDelay,现在效果很好。
    【解决方案2】:

    尝试使用发件人本身,而不是在您的方法中创建新按钮.. 并将发件人的类型更改为(UIButton *)(仅在不使用(id)时才更改)

    - (IBAction)onClickCheckAnswer:(UIButton *)sender

      if([[sender title]isEqual:[currentWord wordTranslate]]){
        [sender setBackgroundColor:[UIColor greenColor]];
    }
    
        else{
            [sender setBackgroundColor:[UIColor redColor]];
        }
    

    :)

    请给个反馈..

    【讨论】:

    • 问题出在 NSThread 睡眠中,但感谢您提供更改按钮背景颜色的好方法)
    【解决方案3】:

    我从您给定的代码中提取了以下几行:

    UIButton *button = (UIButton *)sender;
    if([[sender title]isEqual:[currentWord wordTranslate]]){
    

    将其更改为以下内容:

    UIButton *button = (UIButton *)sender;
    if([[button titleForState:UIControlStateNormal] isEqual:[currentWord wordTranslate]]){
    

    那么,我相信它应该可以工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-24
      • 1970-01-01
      • 2017-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多