【问题标题】:Activity Indicator does not show correctly活动指示器未正确显示
【发布时间】:2015-05-30 01:06:18
【问题描述】:

我试图通过在用户单击“保存”按钮时显示活动指示器来创建与服务器的“模拟”交互。 (完成的应用程序实际上将与服务器交互)我为保存按钮设置了一个 IBAction,我正在调用 activityIndi​​cator,对其进行动画处理,然后暂停。最后,活动指示器隐藏。唯一的问题,活动指示器没有显示。如果我注释掉NSThread.sleepForTimeInterval(4)activityIndicatory.stopAnimating,则显示活动指示。我试图将它们从保存按钮的 IBAction 中移出,但这导致代码出错。代码如下:

@IBAction func saveDTrans(sender: UIBarButtonItem) {

    activityIndicator.hidden = false
    activityIndicator.startAnimating()

    //pause code to let the activityIndicator show for a bit
    NSThread.sleepForTimeInterval(4)

    activityIndicator.stopAnimating()
    activityIndicator.hidden = true
}

【问题讨论】:

  • 我看到很多用于构建活动指示器的代码,我在其他地方的应用程序中也有这些代码。对于这个问题,我只是在视图中放置了一个带有 IBOutlet 的 activityIndi​​cator。我将使用您示例中的一些代码为我的 activityIndi​​cator 添加标签。谢谢你。
  • 不幸的是,我仍然有尝试调用我的 activityIndi​​cator 的问题,暂停 4 秒然后隐藏 activityIndi​​cator。

标签: swift activity-indicator


【解决方案1】:

我不认为你想告诉线程休眠,因为这是主线程并且活动指示器不会运行。这也不是好习惯。

你最好把它放在一个 dispatch_after 块中

@IBAction func saveDTrans(sender: UIBarButtonItem) 
{
    activityIndicator.hidden = false
    activityIndicator.startAnimating()

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 4 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) {
        activityIndicator.stopAnimating()
        activityIndicator.hidden = true
    }
}

【讨论】:

  • 我继续寻找解决方案,并在这段代码中遇到了另一个类似的问题。我复制并粘贴了您的建议,但出现多个错误。 “一行中的连续语句必须用 ',' 分隔”、“调用中的参数 2 缺少参数”、“表达式解析为未使用的函数”、“带括号的语句块是未使用的闭包”、“预期的表达式”。我不知道从哪里开始。
【解决方案2】:

下面的代码将停止主线程:

NSThread.sleepForTimeInterval(4)

试试这个:

@IBAction func saveDTrans(sender: UIBarButtonItem) {

    activityIndicator.hidden = false
    activityIndicator.startAnimating()

    let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * Double(NSEC_PER_SEC)))
    dispatch_after(delayTime, dispatch_get_main_queue()) {
        activityIndicator.stopAnimating()
        activityIndicator.hidden = true
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-25
    • 2021-12-22
    • 2019-02-04
    • 2016-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多