从tableView中选择项目后触发另一个函数后执行函数

问题描述 投票:-1回答:4

当我在tableView中选择一个项目时,我希望在触发第二个goToSegue之前执行第一个func,fetchChosenExerciseData。我该如何实现呢?我看过完成块,但无济于事。

我的代码片段如下:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let cell = tableView.cellForRow(at: indexPath) as! UITableViewCell
    exerciseChosen = cell.textLabel!.text!
    duplicatesRemovedFromSetDataList.removeAll()
    fetchChosenExerciseData()
    goToSegue()

提前致谢。

swift func completionhandler
4个回答
1
投票

由于fetchChosenExerciseData是异步的,因此您需要这种结构

func fetchChosenExerciseData(completion:@escaping()->()) {
    Api.load { 
        completion()
    }
}

呼叫

fetchChosenExerciseData { 
    goToSegue()
}

0
投票

这是完全可以使用完成处理程序:

func fetchChosenExerciseData(_ completion: @escaping () -> Void) {
     // do what you need
     completion()
}

在你的didSelectRowAt你可以插入你的第二个功能

fetchChosenExerciseData {
    // goToSegue
}

0
投票

看来你的函数fetchChosenExerciseData有一些异步部分或一些代码正在不同的Queue上执行。

对于这样的条件,您应该使用完成块。所以你必须像这样声明`fetchChosenExerciseData'

func fetchChosenExerciseData (completion (()->()))
{
// Enter your code 
completion()
}

我已经读过你已经完成了这个解决方案,但我相信一定有一些错误


0
投票

首先将完成块添加到你的方法fetchChosenExerciseData之类的

func fetchChosenExerciseData(finished: () -> Void) {
     print("Doing something whatever you want!")
     finished()
}

然后从你的第一个方法的完成块调用你的函数goToSegue

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let cell = tableView.cellForRow(at: indexPath) as! UITableViewCell
    exerciseChosen = cell.textLabel!.text!
    duplicatesRemovedFromSetDataList.removeAll()
    fetchChosenExerciseData{
    goToSegue()
   }
}

希望这有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.