【发布时间】:2018-09-15 03:45:13
【问题描述】:
我想在我的 Swift 应用程序中使用 ANDLineChartView,这是一个用 Objective C 编写的 API,用于在 ios 中将图表创建为视图。到目前为止,我尝试的只是将 Objective-C 源代码添加到我的 swift 项目中,并添加一个带有一行代码的桥接头(obj-c):
#import "AndLineChartView.h"
这允许我在我的 swift 代码中创建 ANDLineChartView 类型的对象。问题是 ANDLineChartView 需要一个符合称为 ANDLineChartViewDataSource 协议的数据源,因此我(在 Swift 中)编写了一个符合该协议的 @objc 类(并且我扩展了 NSObject,因此它也符合 NSObjectProtocol,这也是必要的) .我在 Swift 中实现了 ANDLineChartViewDataSource 所需的所有必要方法,最后添加了:
#import "MyProjectName-Swift.h"
其中 MyProjectName 当然是我对 ANDLineChartView.m 的项目名称。根据我在互联网上了解到的情况,这是在 Swift 项目中使用 Objective C 代码的标准方法,反之亦然。因此,我继续创建 ANDLineChartView 的实例并将其 dataSource 属性设置为实现 ANDLineChartViewDataSource 的类的实例。
*** -[ANDLineChartView numberOfElements] 中的断言失败,/path/ANDLineChartView.m:158 数据源未设置。
由 ANDLineChartView.m 中的这些代码行生成:
- (NSUInteger)numberOfElements{
if(_dataSource && [_dataSource respondsToSelector:@selector(numberOfElementsInChartView:)]){
return [_dataSource numberOfElementsInChartView:self];
}else{
NSAssert(_dataSource, @"Data source is not set.");
NSAssert([_dataSource respondsToSelector:@selector(numberOfElementsInChartView:)], @"numberOfElementsInChartView: not implemented.");
return 0;
}
}
我的第一个想法是我的函数作为 Objective C 选择器不可见,所以我更改了 NSObjects 响应(到 aSelector : Selector!) -> Bool 方法:
public override func responds(to aSelector: Selector!) -> Bool {
if aSelector == #selector(numberOfElements(in:)) ||
aSelector == #selector(numberOfGridIntervals(in:)) ||
aSelector == #selector(chartView(_:valueForElementAtRow:)) ||
aSelector == #selector(chartView(_:descriptionForGridIntervalValue:)) ||
aSelector == #selector(maxValueForGridInterval(in:)) ||
aSelector == #selector(minValueForGridInterval(in:)) {
return true
} else {
return super.responds(to: aSelector)
}
}
这是我对图表和数据源的声明:
third = ANDLineChartView(frame : CGRect(x : 0,
y : 0,
width : UIScreen.main.bounds.width,
height : Main.screenSegment * 9.5))
third.dataSource = GoalData(data: UserData.past)
其中 GoalData 是我的 ANDChartViewDataSource 类,它使用数组 UserData.past 进行初始化。
尽管如此,我仍然收到相同的错误消息,并且在这一点上,特别是因为我之前在我的项目中甚至没有使用过桥接头等,所以我来这里寻求帮助。我也不了解Objective C,因此与在Objective C 中重写我的dataSource 类无关的解决方案会很棒。或者,如果您对用 Swift 编写的图表 API 有任何建议,那也会很有帮助,因为这样我就不必担心这个了。但我也真的很好奇,所以......
非常感谢您的帮助。
【问题讨论】:
-
错误信息显示Data source is not set.。这意味着在需要时尚未设置
ANDLineChartView的dataSource属性。请在设置ANDLineChartView的位置显示您的 Swift 代码。另外,您无需在库的 .m 文件中添加#import "MyProjectName-Swift.h",除非您修改了库的其他部分。 -
好的,我添加了实例和数据源的声明。
-
dataSource是一个弱属性。您需要在其他地方保持对 dataSource 实例的强引用。 -
请自行发布答案。
标签: ios objective-c swift swift4