我正在尝试做这样的事情:
public extension UIImage {
public convenience init(whatever: Int) {
UIGraphicsBeginImageContextWithOptions(...)
//...
let image = UIGraphicsGetImageFromCurrentContext()
UIGraphicsEndImageContext()
return image // <- impossible
}
}
但是这不可能,因为“ nil”是初始化程序的唯一有效返回值...我该怎么做?
例如,Objtive-C方法[UIImage imageNamed:]是一个类方法(可以在Objective-C中返回所需的任何内容,并且已映射到快速初始化程序UIImage(named:)。
init
完成所需的操作,则可以添加新的类方法:public extension UIImage {
class func imageWithWhatever(whatever: Int) -> UIImage {
UIGraphicsBeginImageContextWithOptions(...)
//...
let image = UIGraphicsGetImageFromCurrentContext()
UIGraphicsEndImageContext()
return image
}
}
public extension UIImage {
public convenience init?(whatever: Int) {
defer {
UIGraphicsEndImageContext()
}
UIGraphicsBeginImageContextWithOptions(...)
//...
guard let currentContext = UIGraphicsGetCurrentContext() else { return nil }
guard let image = currentContext.makeImage() else { return nil }
self.init(cgImage:image)
}
}
也许不是方便的初始化,而是要创建一个执行您所要求的类的函数:
public class func createImage(whatever: Int) -> UIImage? { defer { UIGraphicsEndImageContext() } UIGraphicsBeginImageContextWithOptions(...) //... guard let currentContext = UIGraphicsGetCurrentContext() else { return nil } guard let cgImage = currentContext.makeImage() else { return nil } let image = UIImage(cgImage: cgImage) return image }
我很抱歉,这不是100%的代码,但这基本上是要点