在循环Swift中更新标签

时间:2016-02-01 08:56:56

标签: swift while-loop uilabel

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

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

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

1 个答案:

答案 0 :(得分:2)

尝试使用以下代码,这肯定会有效。

 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更新代码粘贴到主线程,如上所示。 原因:您无法从后台主题更新您的用户界面。