2017-05-28 89 views
1

在Web請求完成後調用enableEndButton()以下函數。在網絡請求後調用UIButton時不會更新

func enableEndButton() { 
    print("Start") 
    buttonState = true 
    go_button.setBackgroundImage(UIImage(named: "stop.png"), for: .normal) 
    go_button.setTitle("Stop", for: .normal) 
    print("Done") 
} 

這兩個打印輸出,但按鈕不會改變,直到我點擊它。我怎樣才能立即發生這種情況?

此功能正在從dataTask中調用按:

let task = URLSession.shared.dataTask(with: url){ 
      data,response,error in 
      if error != nil { 
       print(error!) 
      } else { 
       weather_condition = self.parseWeatherJSON(weatherJSON: data!) 
       //do something with weather_condition 
       self.enableEndButton() 
+0

你的代碼在哪裏調用這個方法?你能舉個例子嗎 – zfetters

+0

它在匿名函數中請求數據,解釋JSON然後在數據 - >之後直接執行一些操作。 – Sam

+0

你能給一個代碼示例嗎?將有助於診斷問題 – zfetters

回答

4

嘗試包裝你到enableEndButton呼叫您URLSession完成在調度

DispatchQueue.main.async { 
    self.enableEndButton() 
} 

編輯:

爲了清楚起見,因爲URLSessions在後臺線程上運行,並且UI更新必須在主線程你做需要將其明確分派給主線程,但是日誌語句不需要在主線程上運行。

+0

就是這樣。爲什麼要打印這些消息,但設置的屬性卻沒有? – Sam

+1

@Sam用更多的信息更新了答案 – zfetters

1

加入這一行,

go_button.isEnabled = true 

呼叫setbackgroundImagesetTitle只要你初始化你的按鈕,

go_button = UIButton() 

// set enabled configuration 
go_button.setBackgroundImage(UIImage(named: "stop.png"), for: .normal) 
go_button.setTitle("Stop", for: .normal) 

// set disabled configuration 
go_button.setBackgroundImage(yourDisabled, for: .disabled) 
go_button.setTitle(disabledTitle, for: .disabled) 
+0

我把這一行放在.setTitle下面,但它不會立即發生(即當「開始」和「完成」是打印機時)...需要10秒鐘+。有任何想法嗎? – Sam

+0

爲了響應您的編輯,我已經將它們初始化爲特定的背景圖像和標題,並且在Web請求完成後嘗試更改它們。 – Sam

+0

您的按鈕是否默認禁用,然後在請求完成後啓用? –

0

我所做的是我總是將屬性設置爲零或e mpty然後更新它們。嘗試下面的功能,希望這會起作用。

go_button.setBackgroundImage(nil, for: .normal) 
go_button.setTitle("", for: .normal) 

在函數的開頭添加這兩行。

+0

不是 - 該按鈕甚至沒有設置爲零。 – Sam

+0

你在使用故事板嗎?在故事板中,您可以選擇爲不同類型設置不同的文字和圖片。在故事板中檢查屬性狀態和選中狀態設置圖像和文本,並在函數中只寫一行。 yourButton.isSelected = true並嘗試將你的函數調用放入Dispatch中。 –

相關問題