我在swift项目中导入了这个Objective-C类。 的 MMLANSCanner.h
#import <Foundation/Foundation.h>
@class Device;
@protocol MMLANScannerDelegate;
@protocol MMLANScannerDelegate <NSObject>
@required
- (void)lanScanDidFinishScanningWithStatus:(MMLanScannerStatus)status;
- (void)lanScanDidFailedToScan;
@optional
- (void)lanScanProgressPinged:(float)pingedHosts from:(NSInteger)overallHosts;
@end
#pragma mark - Public methods
@interface MMLANScanner : NSObject
-(instancetype)initWithDelegate:(id <MMLANScannerDelegate>)delegate;
@property(nonatomic,weak) id<MMLANScannerDelegate> delegate;
@property(nonatomic,assign,readonly)BOOL isScanning;
- (void)start;
- (void)stop;
@end
我成功创建了桥接头并使MainVC.Swift符合MMLANScannerDelegate。
然后我尝试使用委托self
初始化MMLanScanner。
import UIKit
import Foundation
class MainVC: UIViewController, MMLANScannerDelegate {
var presenter = MMLANScanner(delegate:self)
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func lanScanDidFindNewDevice(_ device: Device!) {
}
func lanScanDidFailedToScan() {
}
func lanScanDidFinishScanning(with status: MMLanScannerStatus) {
}
func lanScanProgressPinged(_ pingedHosts: Float, from overallHosts: Int) {
}
}
但我得到错误:
传递给不带参数的调用的参数
如何实现我在Objective-C中使用的initWithDelegate函数?
答案 0 :(得分:1)
MLANScanner
不会将delegate
参数设为init
方法(delegate
是MLANScanner
的属性
您的presenter
属性定义也存在问题,因为self
在创建MainVC
时无效。
请改为:
let presenter = MLANScanner()
override func viewDidLoad() {
super.viewDidLoad()
presenter.delegate = self
}
基于编辑问题:
var presenter: MLANScanner!
override func viewDidLoad() {
super.viewDidLoad()
presenter = MLANScanner(delegate: self)
}
注意:我编辑的答案假定在某处有一个暴露init(delegate:)
方法的Swift桥。可能没有,并且使一个超出了这个问题的范围。由于委托不是私有或只读,因此几乎可以肯定使用我发布的第一个版本。