簡體   English   中英

UIButton圖像在“for”循環中不會發生變化

[英]UIButton Image doesn't changes in a “for” loop


我有個問題:
我設計的GUI沒有InterfaceBuilder,
現在我想在短時間內更改按鈕的圖像,但是在整個for循環完成之前它不會改變。 我究竟做錯了什么?

    for (size_t i=0; i< 100; ++i){
      switch (variable) {
        case 0:
          [self changeRedButtonToWhite: redButton];
        break;
        case 1:
        ....
      }
    }

-(IBAction) changeRedButtonToWhite: (id)sender{
    [sender setBackgroundImage: whiteImage forState: UIControlStateNormal];
}

您不能使用for循環來執行此操作,您應該嘗試使用NSTimer 在主線程內部發生循環時,UI不會刷新。

@ Luzal的解釋是正確的。 您正在設置按鈕的背景顏色,但這只會導致按鈕被標記為需要重繪。 重新繪制不會發生(至少),直到執行返回到運行循環,並且在for循環結束之前不會發生。

我們無法從你發布的代碼中看出你在循環中做了什么,但如果你將它用作延遲機制,然后將按鈕顏色改回紅色,比如variable命中99,那就是反正不是一個好計划。 您可以使用NSTimer來管理顏色更改的持續時間,或使用-performSelector:afterDelay:或使用Core Animation。

將for循環放在后台線程上並在主線程上調用-changeRedButtonToWhite。

你能不能做到以下幾點?

將所有按鈕添加到NSMutableArray ,或者如果您沒有計划在分配后添加更多按鈕,則只需使用NSArray

NSMutableArray *buttonsArray = [[NSMutableArray alloc] initWithObjects:button1, button2, button3, nil]; //and so on....

接着....

for(UIButton *button in buttonsArray){
     [button setBackgroundImage: whiteImage forState: UIControlStateNormal];
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM