转换swift 3中的目标块。
.h文件
@property (nonatomic, copy) void (^clickHandler)(NSString* identifier, CAShapeLayer* layer);
.m文件
[_svgMapview setClickHandler:^(NSString* identifier, CAShapeLayer* layer) {
NSString *countryName = [[NSLocale systemLocale] displayNameForKey:NSLocaleCountryCode value:identifier];
NSLog(@"identifier = %@ & country:%@",identifier,countryName);
layer.backgroundColor = [UIColor redColor].CGColor;
layer.fillColor = [UIColor redColor].CGColor;
}];
当我在线转换时,它看起来像这样...
svgMapview.clickHandler = {(_ identifier: String, _ layer: CAShapeLayer) -> Void in
var countryName: String? = NSLocale.system.displayName(forKey: NSLocaleCountryCode, value: identifier)
print("identifier = (identifier) & country:(countryName)")
layer.backgroundColor = UIColor.red.cgColor
layer.fillColor = UIColor.red.cgColor
}
但是,它在项目中不起作用。
我看到一个可以修复的错别字:
svgMapview.clickHandler = {(_ identifier: String?, _ layer: CAShapeLayer?) -> Void in
guard let actualLayer = layer, let actualIdentifier = identifier
{
print("layer or identifier is nil for some unknown reason")
return
}
// countryName is an optional and it should be immutable, too...
if let countryName = NSLocale.system.displayName(forKey: NSLocaleCountryCode, value: identifier)
{
print("identifier = (actualIdentifier) & country:(countryName)")
actualLayer.backgroundColor = UIColor.red.cgColor
actualLayer.fillColor = UIColor.red.cgColor
} else {
print("couldn't get NSLocale country code")
}
}
如果它仍然不起作用,则应尝试检查该处理程序是否在主(UI)线程上运行。
有一个网站,您可以轻松地将Objective -C代码转换为Swift: -
https://objectivec2swift.com/#/home/main