【问题标题】:How to call a function from another controller in swift如何快速从另一个控制器调用函数
【发布时间】:2019-10-18 14:10:36
【问题描述】:

我在 DetailView Controller 上设置了 Show Charts 按钮,它触发 getChartData 函数并在图表的显示视图中显示值,现在我想在主 Viewcontroller 上的 didselectrow 中调用该函数,以便自动加载图表,但它失败了。 当我尝试在 didselectrow (DVC.getChartsData) 中调用该函数时,出现错误“线程 1:致命错误:在隐式展开可选值时意外发现 nil”

DVC.getChartsData

线程 1:致命错误:在隐式展开可选值时意外发现 nil

视图控制器:

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {        
        let Storyboard = UIStoryboard(name: "Main", bundle: nil)
        let DVC = Storyboard.instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController
        DVC.getDetailName = coin[indexPath.row].name
        let formatedRoundingPrice = (coin[indexPath.row].price as NSString).floatValue * currencymodel.indexValue
        let formatedPrice = String (format: "%.3f", formatedRoundingPrice)
        DVC.getDetailPrice = formatedPrice
        self.navigationController?.pushViewController(DVC, animated: true)
        let percentage = String ((coin[indexPath.row].percent as NSString).floatValue)
        DVC.getDetailPercent = percentage
        tableView.deselectRow(at: indexPath, animated: true)
        //DVC.getChartData()
}

DetailViewController:

    @IBAction func tapLineChart(_ sender: Any) {


       getChartData()


    }

    func getChartData () {

        let chart = HITLineChartView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: displayView.bounds.height))
        displayView.addSubview(chart)
        let max = String((priceResult.max() ?? 0.0).rounded(.up))
        let min = String((priceResult.min() ?? 0.0).rounded(.down))
        let maxChange = abs((listOfChanges.max()) ?? 0.0).rounded(.up)
        let minChange = abs((listOfChanges.min()) ?? 0.0).rounded(.up)
        absMaxPercentage = Int(maxChange > minChange ? maxChange : minChange)
        titles = ["\(getDetailName) closing price is \(getDetailPrice)"]

        print(data)
        chart.draw(absMaxPercentage,
                   values: listOfChanges,
                   label: (max: max, center: "", min: min),
                   dates: namesArray,
                   titles: titles)

        addCloseEvent(chart)

        finalURL = baseURL + "bitcoin" + "/market_chart?vs_currency=usd&days=5"
        print(finalURL)
        getBitcoinData(url: finalURL)

    }

如何加载我的图表点击特定的表格视图单元格而不是点击 TapLineChart。

https://imgur.com/fg2502P

https://imgur.com/C4AzaRY

https://imgur.com/jOrwujy

【问题讨论】:

  • 您需要做的就是从您的 DetailViewController 的 viewDidLoad 调用 getChartData()。

标签: swift function uiviewcontroller didselectrowatindexpath


【解决方案1】:

如果你想在 viewControllerB 上调用你从 viewController A 声明的函数。

只需创建要使用函数的类文件的对象

var obj mainVC = MainViewController()



class MainViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
    func commonMethod() {
        print("From the main class")
    }
}

使用该对象,在您打算使用它的另一个文件中调用该函数

class OtherViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        mainVC.commonMethod()
        // Do any additional setup after loading the view, typically from a nib.
    }
}

此外,您还可以创建一个新的 swift 文件,将其命名为 Global.swift,在此处创建您想要在整个应用程序中使用的所有函数。它们成为“全局函数”

【讨论】:

  • 我没想到这会奏效,但它确实有效:D 太棒了!
【解决方案2】:

您将希望使用委托或观察者在视图控制器之间传递数据。

我是教程新手,但我在这里写了一点:https://www.eankrenzin.com/swift-blog/pass-data-throughout-your-app-with-observers-and-notifications-xcode-11-amp-swift-5

你应该使用可选绑定来解开你的 VC let DVC = Storyboard.instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController

您的代码因为该行而崩溃。检查您的界面生成器以确保标识符正确。编辑:此行没有导致崩溃,但使用可选绑定仍然更好。该行是:https://imgur.com/CVP1x6H

注意:当委托和观察者可以工作时,在你的应用程序中乱扔实例是一种糟糕的做法。也没有全局变量。 Globals 在调试和制造技术债务方面是灾难性的。

【讨论】:

  • 谢谢 ekrezin,我会尝试使用委托或通知。
  • app chrash 在这一行: let chart = HITLineChartView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: displayView.bounds.height)) displayView.addSubview(chart) 它不是情节提要 init imgur.com/CVP1x6H
  • 嗯,我的错误,我错误地假设你是用不正确的storyboardID强制解包(!),这是我遇到过很多次的错误,所以我经常寻找它。 nil 错误意味着某些可选选项在某个阶段被强制解包。您在该类中是否有任何隐式展开的变量?还要检查是否可以毫无问题地向 displayview 添加另一个视图。最终,当您实现委托或观察者时,您将能够更顺畅地调用这些函数,从而解决这些问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多