ios - 错误 : Initializers may only be declared within a type

标签 ios swift

这是我的代码

extension UIImage {
    convenience init(color: UIColor, size: CGSize = CGSizeMake(1, 1)) {
        let rect = CGRectMake(0, 0, size.width, size.height)
        UIGraphicsBeginImageContext(rect.size)

        let context = UIGraphicsGetCurrentContext()
        CGContextSetFillColorWithColor(context, color.CGColor)
        CGContextFillRect(context, rect)

        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        init(CGImage: image.CGImage!)
    }
}

init(CGImage: image.CGImage!) 上,我得到了错误

Initializers may only be declared within a type

最佳答案

专用初始化器从便利初始化器调用 使用 self.init(...):

self.init(CGImage: image.CGImage!)

没有self.(或super.,如果你调用父类(super class)初始化器) 编译器将 init(...) 误认为是 init 的 declaration 方法。

关于ios - 错误 : Initializers may only be declared within a type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34328602/

相关文章:

ios - UIScrollView 在缩放或滚动时阻止所有触摸

ios - 添加行后如何更新 UITableView?

ios - 串行队列/专用调度队列如何知道任务何时完成?

ios - 使用 Storyboard 以编程方式设置初始 View Controller

ios - swift:在 Collection View 中的标签中显示进度

ios - 从rss中获取图片URL

ios - 在 UILabel 之后放置一个 UIImage

objective-c - 在 Swift 中将后台任务作为循环运行

java - Swift 或 Objective C 中的 java ByteBuffer 等价于什么?

swift - 无法使用 MobileHub 从 DynamoDB 检索数据