【问题标题】:Swift TableView Cell - Show Activity Spinner, Perform Function, Hide Activity SpinnerSwift TableView Cell - 显示活动微调器,执行功能,隐藏活动微调器
【发布时间】:2016-04-30 07:09:18
【问题描述】:

我正在 Swift 中构建一个显示 UITableView 单元列表的应用程序。当用户点击一个单元格时,我希望按顺序执行以下操作:

  1. 取消选择索引路径处的行
  2. 显示 UIActivitySpinner 并为其设置动画
  3. 执行一项功能(大约持续 10 秒)
  4. 隐藏 UIActivitySpinner

我目前的代码如下:

     override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

             self.tableView.deselectRowAtIndexPath(indexPath, animated: true)

             let cell = tableView.cellForRowAtIndexPath(indexPath) as! TableViewCell

             cell.ActivitySpinner.startAnimating()

             myFunction() // Approximately 10 seconds.

             cell.ActivitySpinner.stopAnimating()

             return
        }

所以这个想法是 UIActivitySpinner 将在 myFunction() 执行时出现 10 秒,并在 myFunction() 完成时消失。

当前的问题是 UIActivitySpinner 仅在 myFunction() 完成执行后出现。我不确定如何让 ActivitySpinner 在 myFunction() 开始之前出现,并在 myFunction() 完成后消失。

关于 myFunction():它是一个 C 函数,链接在桥接头中,主要是 HTTP 请求。

【问题讨论】:

    标签: swift uitableview


    【解决方案1】:

    首先,使用大写属性的第一个字母通常不是最佳做法。

    如果您制作像网络调用这样的异步线程,那么下面这不是最好的解决方案。 你可以使用这个功能(我不推荐这个):

    func dispatchDelay(delay:Double, closure:()->()) {
        dispatch_after(
            dispatch_time(
                DISPATCH_TIME_NOW,
                Int64(delay * Double(NSEC_PER_SEC))
            ),
            dispatch_get_main_queue(), closure)
    }
    

    .. 然后做:

    cell.ActivitySpinner.startAnimating()
    myFunction() // Approximately 10 seconds.
    dispatchDelay(10.0) {
         cell.ActivitySpinner.stopAnimating()
    }
    

    这是我给你的建议:

    你必须像这个例子一样将完成处理程序添加到你的 C 函数中:

    void myFunction(std::string urlStr, std::function<void(std::string)> callback)
    {
      ...
      NSURLSessionDataTask* dataTask = 
        [defaultSession 
          dataTaskWithURL:url 
          completionHandler:
            ^(NSData *data, NSURLResponse *response, NSError *error) {
              if(error == nil)
              {
                 NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
                 NSLog(@"Data = %@",text);
    
                 // invoke the callback here...
                 callback(std::string([text UTF8String]));
              }
            }];
      ...
    }
    

    在 C 中你可以像这样使用它:

    void callbackFunc(std::string data)
    {
      ...
    }
    
    myFunction("...", callbackFunc);
    

    你现在需要构建的是一个跨平台的 C -> Swift,如果你不知道,你可以按照这些指令“Building cross platform aint easy”:这可以让你将回调集成到你的 swift 代码中来处理确切的 myFunction 开始时间和结束时间。

    【讨论】:

    • 非常感谢,这是很大的帮助。完成处理程序是否适用于 Obj C BOOL 函数?
    • 当然,您可以将 c 函数包装到 obj c 并将其桥接到 swift,这在答案“Building cross..”中的链接中有详细说明
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-27
    • 2021-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-11
    相关资源
    最近更新 更多