标签在回调 swift 中不更改 3.



我想在收到服务器的响应后更改我的标签文本,但在收到服务器的响应后它没有改变!!

这是我的代码:

func getOrderCost() {
    DispatchQueue.main.async {
        self.customView?.setOrderPriceEstimate(price: "۰")
        var price = 10
        if let p_code = self.customView?.getPromotionCode() {
            self.orderPriceObject.promotion_code = p_code
        }  
        self.registerOrderVM.getOrderPriceEstimation(orderInfo: self.orderPriceObject).asObservable().subscribe(onNext: { (response) in
            if let res = response as? [String: Int], let p = res["price_with_added_value"] {
                self.customView?.setOrderPriceEstimate(price: "cost : (p)")
            }
        }, onError: { (error) in
            self.view.showMessage(error.localizedDescription, type: .error, options: [.hideOnTap(true)])
        }).disposed(by: self.disposeBag)
    }
}

这是customView中的setOrderPriceEstimate函数:

public func setOrderPriceEstimate(price: String) {
    self.orderCostLbl.text = price
}
DispatchQueue.main.async {
        self.customView?.setOrderPriceEstimate(price: "cost : (p)")
    }

我认为您必须在主线程中更新 UI。

DispatchQueue.main.async 外在并不能保证 getOrderPriceEstimation 中的代码将在主队列中运行,因为 getOrder 中的代码可能在其他线程中

    func getOrderCost() {
        DispatchQueue.main.async {
            self.customView?.setOrderPriceEstimate(price: "۰")
            var price = 10
            if let p_code = self.customView?.getPromotionCode() {
                self.orderPriceObject.promotion_code = p_code
            }

            self.registerOrderVM.getOrderPriceEstimation(orderInfo: self.orderPriceObject).asObservable().subscribe(onNext: { (response) in

                if let res = response as? [String: Int], let p = res["price_with_added_value"] {
              DispatchQueue.main.async {
                    self.customView?.setOrderPriceEstimate(price: "cost : (p)")
                  }
                }
            }, onError: { (error) in
                self.view.showMessage(error.localizedDescription, type: .error, options: [.hideOnTap(true)])
            }).disposed(by: self.disposeBag)
        }
    }

验证 P 是否存在

if let res = response as? [String: Int], let p = res["price_with_added_value"] {
                  DispatchQueue.main.async {
                self.customView?.setOrderPriceEstimate(price: "cost : (p)")          }
            }
     else
    {
       print("res or p is not found")
    }

还要检查自定义视图是否为零

最新更新