【问题标题】:How to access swift resources in objective c?如何在目标 c 中访问 swift 资源?
【发布时间】:2015-12-30 07:18:06
【问题描述】:

我想在 ViewController 文件中显示图表。我可以在 swift 文件中显示图表。我的问题是,我想在 viewController 文件中访问该视图。但无法访问。我可以调用来自 viewController 的方法 test() 但无法调用 setChart() 方法。这是我的源代码:

ViewController.m

#import "ViewController.h"
#import "ChartsDemo-swift.h"
#import "ChartsDemo-Bridging-Header.h"
@interface ViewController ()

@end

@implementation ViewController
- (void)viewDidLoad 
{
    [super viewDidLoad];
    //View Creation
    UIView *mainView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 200, 270)];

    //Array Creation
    NSMutableArray *mn = [[NSMutableArray alloc]initWithObjects:@"5",@"8", nil];
    NSArray *un = [[NSArray alloc]initWithObjects:@"6",@"10", nil];

    //Instance for Swift Class
    BarChartViewController *bcv = [[BarChartViewController alloc]init];

    //Function Call
    [bcv test];
    [bcv setChart:mn values:un];
}

- (void)didReceiveMemoryWarning 
{
    [super didReceiveMemoryWarning];
}

@end

BarChartViewController.swift

import Foundation
import Charts

class BarChartViewController: UIViewController {

@IBOutlet var barChartView: BarChartView!
var months: [String]!

override func viewDidLoad()
{

    //Array Creation
     months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
    let units = [20.0, 4.0, 6.0, 3.0, 12.0, 16.0, 4.0, 18.0, 2.0, 4.0, 5.0, 4.0]

   //Function call
    setChart(months, values: units)
    piesetChart(months, values: units)

}

func test()
{
    print("hi")
}


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

    var dataEntries: [BarChartDataEntry] = []

    for var i=0; i < dataPoints.count; i++
    {
        let dataEntry = BarChartDataEntry(value: values[i], xIndex: i)
        dataEntries.append(dataEntry)
    }

    let chartDataSet = BarChartDataSet(yVals: dataEntries, label: "Units Sold")
    let chartData = BarChartData(xVals: months, dataSet: chartDataSet)

    chartDataSet.colors = [UIColor .redColor()]

    barChartView.data = chartData
    barChartView.xAxis.labelPosition = .Bottom
}

1.如何在Objective c视图中访问swift视图?

2.如何从ViewController.m中访问setChart方法?

【问题讨论】:

    标签: ios objective-c swift methods


    【解决方案1】:

    如果您想从您的ViewController.m 方法访问setChart() 方法,

    1. ViewController.m中导入Bridging-Header.h

    2. ViewController 类中为BarChartViewController.swift 创建一个实例。通过使用实例,您可以访问setChart() 方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-10
      • 2023-03-22
      • 2016-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多