如何在同一项目中使用其他swift文件(相同目标)中的功能

时间:2019-06-05 13:44:40

标签: swift file

嘿,我自己的swift文件中有2个类。我基本上这样做只是为了在Viewcontroller中获得更好的概述。不过,我仍然需要访问数据或从视图controller.swift文件中的其他文件调用func。它在同一Target中,因此我不需要将其导入我的视图控制器文件中吗?

如果我确实覆盖了func viewDidLoad(),则会得到一个异常,所以我想我只能执行一次(在我的viewController.swift中为->)

// ViewController.swift

class ViewController: UIViewController{


    @IBOutlet weak var xMotion: UILabel!
    @IBOutlet weak var yMotion: UILabel!
    @IBOutlet weak var zMotion: UILabel!

    @IBOutlet weak var lineChartView: LineChartView!
    @IBOutlet weak var lineChartView2: LineChartView!


override func viewDidLoad() {
    super.viewDidLoad()

       timebuffer.append(Double(ts1))
       colors.append(UIColor.red)

       Graphen.customizeChart(values: buffer1.map { Double($0) })
       Graphen.filteredChart(values: buffer2.map { Double($0) })
       Graphen.multipleCharts()
}

// Graphen.swift

class Graphen : ViewController
{

    //creates Plot with specific numbers/data
    func customizeChart(values: [Double]){
        var dataEntries: [ChartDataEntry] = []
        for i in 0..<buffer1.count{//dataPoints.count
            let dataEntry = ChartDataEntry(x: Double(i), y: values[i])
            dataEntries.append(dataEntry) }
        lineChartDataSet = LineChartDataSet(entries: dataEntries, label: nil)
        lineChartDataSet.circleRadius = 0.5
        let lineChartData = LineChartData(dataSet: lineChartDataSet)
        self.lineChartView.data = lineChartData
    }
}

1 个答案:

答案 0 :(得分:1)

viewDidLoad()lifecycle method中的UIViewController's instance。因此,它可以是每个overridden UIViewCiontroller中的subclass,即

class ViewController: UIViewController{
    override func viewDidLoad() {
        super.viewDidLoad()
        //your code here...
    }
}


class Graphen : ViewController
{
    override func viewDidLoad() {
        super.viewDidLoad()
        //your code here...
    }
}

现在,您无需导入任何file/class,只要它们在同一个target中即可。

现在,由于Graphen's customizeChart(values:)方法是instance method,因此您需要先创建instance的{​​{1}},然后使用它来调用这样的实例方法,

Graphen

类似地调用let graphen = Graphen() graphen.customizeChart(values: buffer1.map { Double($0) }) 中的其他instance methods。假设GraphenfilteredChart(values:)也是multipleCharts(),您可以像这样调用它们,

instance methods