在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
}
但是,它不适用于项目。
答案 0 :(得分:4)
我看到一个可以解决的拼写错误:
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)线程上运行该处理程序。
答案 1 :(得分:0)
有一个网站,您可以轻松地将目标-c代码转换为swift: -