在Web请求后调用UIButton时不会更新

时间:2017-05-28 14:56:47

标签: ios swift uibutton

我在Web请求完成后调用了以下函数enableEndButton()

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()

3 个答案:

答案 0 :(得分:4)

尝试在调度中完成URLSession完成中对enableEndButton的调用

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

编辑:

为了清楚起见,因为URLSessions在后台线程上运行,UI更新必须在主线程上完成,您需要将它显式地分配给主线程,但是不需要在主线程上运行日志语句。

答案 1 :(得分: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)

答案 2 :(得分:0)

我所做的是我总是将属性设置为nil或empty,然后更新它们。尝试下面的功能希望这会起作用。

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

在功能开始时添加这两行。