以下代码取自FastImageCache git存储库。我怎么能在Swift中写这个?
FICEntityImageDrawingBlock drawingBlock = ^(CGContextRef context, CGSize contextSize)
{
CGRect contextBounds = CGRectZero;
contextBounds.size = contextSize;
CGContextClearRect(context, contextBounds);
....
UIGraphicsPopContext();
};
答案 0 :(得分:2)
试试这个:
let drawingBlock: FICEntityImageDrawingBlock = { context, contextSize in
let contextBounds = CGRectZero
contextBounds.size = contextSize
CGContextClearRect(context, contextBounds)
...
UIGraphicsPopContext()
}
答案 1 :(得分:1)
这就是它的外观,主要变化是第一行,您使用(parameters) in
。
let drawingBlock: FICEntityImageDrawingBlock = { (context: CGContextRef, size: CGSize) in
let bounds = CGRect(origin: .zero, size: size)
CGContextClearRect(context, bounds);
//...
UIGraphicsPopContext();
}
答案 2 :(得分:1)
我已将目标C块代码转换为Swift代码...
// Object-C FICEntityImageDrawingBlock definition
// void (^FICEntityImageDrawingBlock)(CGContextRef context, CGSize contextSize);
// Swift code
let drawingBlock : FICEntityImageDrawingBlock = {( context, contextSize) in
var contextBounds : CGRect = CGRectZero;
contextBounds.size = contextSize;
CGContextClearRect(context, contextBounds);
UIGraphicsPopContext();
}
您还可以非常轻松地将任何Objective-C块代码转换为swift代码。看看另一个例子 -
// Objecttive C Block
void (^completionBlock)(NSData *, NSError *) = ^(NSData *data, NSError *error) {
// ...
}
// Swift Block
let completionBlock: (NSData, NSError) -> Void = { (data, error) in
// ...
}
有关详细信息,请参阅apple documentation