简体   繁体   中英

Prevent App Crash incase image renamed / deleted from Xcode

I have set logo image in my UIImageView & runs and it's working fine, but in case someone removed / renamed image by mistake then & runs again and my app crashes because Xcode can't find that image. Here I need to implement that if such images are not found by Xcode due to renamed / removed then its not crashed but some placeholder image should be set & it's globally too in project for all the UIImageViews. So could anyone help me in this. Thanks in advance.

在此输入图像描述

在此输入图像描述

在此输入图像描述

Quoc Nguyen is correct. You can just use image literal name. Like so:

private lazy var logoImageView: UIImageView = {
    let imageView = UIImageView(image: UIImage(named: "swift_logo"))
    imageView.translatesAutoresizingMaskIntoConstraints = false
    return imageView
}()

The UIImageView initialiser method can take an optional UIImage object:

init(image: UIImage?)

And the UIImage initialiser method using name produces optional UIImage object.

init?(named name: String)

That means, you can use it safely. Regardless if your logo exists or not. I hope this helps!

UPDATE:

You can make your own extension of UIImage class to declare your assets, so that when time comes that you need to rename an asset, you'll have to rename it once and the changes will be applied all throughout your project (globally, as you say).

import UIKit

/// A category for handling images
extension UIImage {

    // MARK: - Home Assets

    static let swiftLogo = UIImage(named: "swift_logo") 
}

and you can use that like so:

private lazy var logoImageView: UIImageView = {
    let imageView = UIImageView(image: .swiftLogo)
    imageView.translatesAutoresizingMaskIntoConstraints = false
    return imageView
}()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM