You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift 3回调中Label文本不更新问题求助

解决服务器响应后Label文本不更新的问题

嘿,我帮你分析下为啥Label文本没更新哈!核心问题在于UI更新操作没在主线程执行。虽然你把整个getOrderCost的逻辑包在了DispatchQueue.main.async里,但RxSwift的网络请求回调(也就是onNext闭包)的执行线程,是由registerOrderVM.getOrderPriceEstimation这个Observable内部的调度器决定的——绝大多数网络请求的Observable默认会在后台线程发送事件,所以你的self.customView?.setOrderPriceEstimate(...)其实是在后台线程跑的,而iOS要求所有UI操作必须在主线程,这就导致Label根本没刷新。

给你两种靠谱的解决方案:

方案一:在回调里手动切回主线程

直接把更新UI的代码放到DispatchQueue.main.async里,确保UI操作在主线程执行:

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
                // 切回主线程更新UI
                DispatchQueue.main.async {
                    if let res = response as? [String: Int], let p = res["price_with_added_value"] {
                        self.customView?.setOrderPriceEstimate(price: "cost : \(p)")
                    }
                }
            }, onError: { (error) in
                // 错误提示也要在主线程哦
                DispatchQueue.main.async {
                    self.view.showMessage(error.localizedDescription, type: .error, options: [.hideOnTap(true)])
                }
            }).disposed(by: self.disposeBag)
    }
}

方案二:用RxSwift的observeOn指定主线程

这是更符合RxSwift风格的做法,通过observeOn(MainScheduler.instance)直接指定后续的订阅逻辑在主线程执行:

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()
            // 强制后续的订阅操作在主线程执行
            .observeOn(MainScheduler.instance)
            .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)
    }
}

另外提个小建议:如果getOrderCost本身是在主线程触发的(比如按钮点击事件里调用),那外层的DispatchQueue.main.async其实是多余的,反而会延迟初始Label的设置,你可以考虑去掉它哦!

内容的提问来源于stack exchange,提问作者Mohsen mokhtari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:06:54