第一个函数仅在执行其他代码后才开始执行

时间:2019-04-18 09:46:51

标签: ios swift uiactivityindicatorview

我具有显示和隐藏活动指示器的功能。当我从tableview删除行时,我想显示活动指示器。但是,当我调用删除操作时,应该首先开始工作的功能showActivityIndicator(),只有在执行fortableview.deleteRowsdeleteAction中的另一个代码之后才能开始工作。为什么showActivityIndicator()最后开始工作?在执行另一段代码之前如何强制函数显示ActivityIndi​​cator?

class TestClass: UIViewController, UITableViewDataSource, UITableViewDelegate {


var container: UIView = UIView()
var loadingView: UIView = UIView()
var activityIndicator: UIActivityIndicatorView = UIActivityIndicatorView()

// MARK: - showActivityIndicator
func showActivityIndicator() {

    // Container that equal iPhone screen size
    container.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height)
    container.center = CGPoint(x: container.frame.midX, y: container.frame.midY)
    container.backgroundColor = UIColor.black.withAlphaComponent(0.6)

    // View for activity indicator
    loadingView.frame = CGRect(x: 0, y: 0, width: 80, height: 80)
    loadingView.center = container.center
    loadingView.backgroundColor = UIColor.black
    loadingView.clipsToBounds = true
    loadingView.layer.cornerRadius = 10

    // Setup activity indicator
    activityIndicator.frame = CGRect(x: 0.0, y: 0.0, width: 40.0, height: 40.0)
    activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.whiteLarge
    activityIndicator.center = CGPoint(x: loadingView.frame.size.width / 2, y: (loadingView.frame.size.height / 2))

    loadingView.addSubview(activityIndicator)
    container.addSubview(loadingView)

    activityIndicator.startAnimating()

    // Show activity indicator
    let window = UIApplication.shared.keyWindow!
    window.addSubview(container)

}

// MARK: - hideActivityIndicator
func hideActivityIndicator() {
    activityIndicator.stopAnimating()
    container.removeFromSuperview()
}

// MARK: - Delete action(swipe)
func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {

    var swipe = UISwipeActionsConfiguration()

    switch segmentedControl.selectedSegmentIndex {

    case 0:

        let deleteAction = UIContextualAction(style: .destructive, title: "Delete") { (action, sourceView, completionHandler) in

            self.showActivityIndicator()

            for i in 0...10000 {

              print("i:",i)

            }

            self.tableView.deleteRows(at: [indexPath], with: .fade)

            completionHandler(true)

            self.fetchData()

            self.tableView.reloadData()

            // self.hideActivityIndicator()

        }

        let swipe1 = UISwipeActionsConfiguration(actions: [deleteAction])

        swipe = swipe1

    case 1:
        break
    default:
        break
    }

    return swipe

}

}

0 个答案:

没有答案