从ViewController调用UIView方法

时间:2016-07-31 10:37:37

标签: ios swift uiview

我为折线图和条形图创建了两个单独的xib文件,并将其链接到场景中的视图。我根据数据类型分配了笔尖。我在我的UIView类中有一个函数setChart(),我需要从我的ViewController调用它来绘制图表。

如何从ViewController调用函数setChart()?我的代码不起作用

的UIView:

class BarChartDashboard: UIView {

@IBOutlet weak var barChartView: BarChartView!

override func awakeFromNib() {
    .....
}

func setChart(dataPoints: [String], values: [Double]) {

    .....
}


}

的ViewController:

class DetailDashboardViewController: UIViewController {

@IBOutlet weak var chartView: UIView!

override func viewDidLoad() {
    super.viewDidLoad()

    runQueries(2)

    if index != 3{
        chartView = NSBundle.mainBundle().loadNibNamed("BarChartDashboard", owner: self, options: nil)[0] as? UIView
    }
    else{
        chartView = NSBundle.mainBundle().loadNibNamed("LineChartDashboard", owner: self, options: nil)[0] as? UIView
    }
}
}

private extension DetailDashboardViewController {

func runQueries(period: Int) {

    self.query(false, periodIndex: period){ (success) -> Void in
        if success {
            // do second task if success
            dispatch_async(dispatch_get_main_queue(), {
                if self.index != 3{
                    (self.chartView as! BarChartDashboard).setChart(self.yAxis, values: self.xAxis)
                }
                else{
                    (self.chartView as! LineChartDashboard).setChartData(self.yAxis, yAxisMax: self.xAxisMax, yAxisMin : self.xAxisMin)
                }
            })
        }
    }
}


func query(min: Bool, periodIndex: Int, completion: (success: Bool) -> Void) {
    .......
}

}

2 个答案:

答案 0 :(得分:1)

DetailDashboardViewController中,当您的自定义UIView类名为UIView时,您已将视图实例设为BarChartDashboard类型,因此为了能够调用方法setChart()您应该将类​​检查器中的视图类设置为BarChartDashboard以及DetailDashboardViewController实例变量应更改如下:

@IBOutlet weak var chartView: BarChartDashboard!

现在,实例变量的类型为BarChartDashboard,现在可以从setChart()调用方法DetailDashboardViewController

DetailDashboardViewController

@IBOutlet weak var chartView: BarChartDashboard!
override func viewDidLoad() {
     super.viewDidLoad()

     runQueries(2)

     if index != 3{
        chartView = NSBundle.mainBundle().loadNibNamed("BarChartDashboard", owner: self, options: nil)[0] as? UIView
     }
     else{
        chartView = NSBundle.mainBundle().loadNibNamed("LineChartDashboard", owner: self, options: nil)[0] as? UIView
     }
     chartView.setChart(dataPoints: ["hello","world"], values: [20.0,21.5])
}

答案 1 :(得分:1)

在ViewController中创建一个新变量id,并将此图表cust_ID添加到与xib相连的timestamp table

您的ViewController类如下所示:

value