在 While 循环 Swift 中更新标签 [英] Update Label In While Loop Swift

查看:16
本文介绍了在 While 循环 Swift 中更新标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我错了,请纠正我,但是当我尝试在 while 循环中更新我的标签时,它不会更新它.是因为 while 循环运行太快,标签无法在该时间内更新,因此会取消标签更新吗?

Correct me if I'm wrong, but when I try to update my label in a while loop it won't update it. Is the reason that the while loop runs too quickly for the label to update within that time so it'll cancel the label from updating?

我需要一个解决方案吗?我需要能够立即更新标签吗?

I need a solution to this? I need to be able to update the label straight away?

func Download(complete: (canMoveOn: Bool) -> Void) {
    isDownload = true

    if (connected!) {
        Reset()

        let data = NSData(contentsOfFile: path!)!
        let buffer = (UnsafeMutablePointer<UInt8>(data.bytes))

        var leftOverSize = data.length
        let bytesFile = data.length
        var totalBytesRead = 0
        var bytesRead = 0

        let stream = CFReadStreamCreateWithFTPURL(nil, downloadURL!).takeUnretainedValue()
        let status = CFReadStreamOpen(stream)

        if (status == true) {
            while (totalBytesRead < bytesFile) {
                bytesRead = CFReadStreamRead(stream, buffer, leftOverSize)

                if (bytesRead > 0) {
                    totalBytesRead += bytesRead

                    if (bytesRead < bytesFile) {
                        leftOverSize = bytesFile - totalBytesRead
                    } else {
                        leftOverSize = 0
                    }
                } else {
                    break
                }

                //-------------Not Updating Label
                downloadLabel.attributedText = NSAttributedString(string: "\(totalBytesSent)", attributes: [NSFontAttributeName: UIFont(name: "Arial", size: 20)!, NSForegroundColorAttributeName: UIColor.darkTextColor()])

                Calculate(bytesRead, totalBytesSent: totalBytesRead, totalBytesExpectedToSend: bytesFile)
            }

            CFReadStreamClose(stream)

            complete(canMoveOn: true)
        } else {
            Error()

            downloadLabel.attributedText = NSAttributedString(string: "- -", attributes: [NSFontAttributeName: UIFont(name: "Arial", size: 20)!, NSForegroundColorAttributeName: UIColor.darkTextColor()])

            complete(canMoveOn: false)
        }
    }
}

推荐答案

尝试下面的代码,这肯定会奏效.

 while (currentSize < fileSize) {

        dispatch_sync(dispatch_get_main_queue(), { () -> Void in
            downloadLabel.attributedText = NSAttributedString(string: "\(currentSize) kbps", attributes: [NSFontAttributeName: UIFont(name: "Arial", size: 20)!, NSForegroundColorAttributeName: UIColor.darkTextColor()])
            });

    }

只需将您的 UI 更新代码粘贴到主线程,如上所示.原因:您无法从后台线程更新您的 UI.

这篇关于在 While 循环 Swift 中更新标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆