swift - 使用新参数初始化 UIImage

标签 swift

<分区>

我怎样才能像 a 那样做 new init

Attention: I need init, not static func

extension UIImage {

    convenience init?(named: String, in bundle: Bundle? = nil, compatibleWith collection: UITraitCollection? = nil, rendring: UIImageRenderingMode) {
        self.init(named: named, in: bundle, compatibleWith: collection)
        self = self.imageWithRenderingMode(rendring) // error
        return
    }

}

但是我在执行时遇到了错误

Error: Cannot assign to value: 'self' is immutable

最佳答案

你可以这样使用:

我是用 Swift 4.1 写的,你可以进行必要的更改。

extension UIImage {
    convenience init?(named: String, in bundle: Bundle? = nil, compatibleWith collection: UITraitCollection? = nil, rendring: UIImageRenderingMode) {
        if let image = UIImage(named: named, in: bundle, compatibleWith: collection) {
            if let cgImage = image.withRenderingMode(rendring).cgImage {
                self.init(cgImage: cgImage)
            }
        }
        return nil
    }
}

关于swift - 使用新参数初始化 UIImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51632395/

相关文章:

ios - Alamofire:参数未传递到服务器

ios - AVAudioPlayer 从后台恢复但暂停其他应用程序

ios - UITextView.attributedText,如何设置numberOflines和lineBreakMode?

closures - animateWithDuration:animations:completion: 在 Swift 中

ios - 背景视频循环无法快速工作

ios - UITableView - 在 sectionHeader 中调整 FontSizeToFitWidth

ios - 在 html 中为 UILabel 属性文本设置字体不起作用

ios - UIView.convert 在计算 UIWindow 中的 UITableViewCell subview 时给出错误的结果

ios - 在 UILabel 上显示 iPhone 剪切复制粘贴菜单

ios - 在 swift 3 中创建 View Controller 的单例