访问 Assets 文件夹中的内部文件夹
Accessing inner folders in Assets folder
我的 Assets.xcassets
文件夹中有以下文件夹
screenshot of the error - sorry, i dont have enough rep to show the image
我正在尝试访问 ca
文件夹,然后是 payments
,然后是里面的图像以填充 UICollectionViewCell
。为了测试,我强制打开它(我知道它不安全):
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CellId, for: indexPath) as! MyCollectionViewCell
cell.paymentImageView.image = UIImage(named: "logos/ca/payments/x.png")!
return cell
我崩溃了,它说:
Fatal error: Unexpectedly found nil while unwrapping an Optional value: file
我不确定它为什么会崩溃,文件在那里。每个国家/地区的不同文件夹中都有多个重复的文件名,这是一个问题吗?即 xyz.png 也可能在 ca/payments 和 de/payments 中
图像不需要完整路径。仅使用名称(如果您直接添加图像)
cell.paymentImageView.image = UIImage(named: "x.png")!
如果您使用的是 .xcassets。使用图像集的名称而不是单个图像
cell.paymentImageView.image = UIImage(named: "<IMAGE_SET_NAME>")!
此崩溃是因为您尝试强制解包可选值。
UIImage(named: "logos/ca/payments/x.png")
是可选值。如果您的项目中不存在图片,则为 nil。
而且我们在获取图片时不需要输入路径,只需要图片名称和扩展文件,如UIImage(named: "x.png")
也cell.paymentImageView.image
可以接受nil图像。所以这一行只有 cell.paymentImageView.image = UIImage(named: "x.png")
就可以了。
希望对您有所帮助!
我的 Assets.xcassets
文件夹中有以下文件夹
screenshot of the error - sorry, i dont have enough rep to show the image
我正在尝试访问 ca
文件夹,然后是 payments
,然后是里面的图像以填充 UICollectionViewCell
。为了测试,我强制打开它(我知道它不安全):
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CellId, for: indexPath) as! MyCollectionViewCell
cell.paymentImageView.image = UIImage(named: "logos/ca/payments/x.png")!
return cell
我崩溃了,它说:
Fatal error: Unexpectedly found nil while unwrapping an Optional value: file
我不确定它为什么会崩溃,文件在那里。每个国家/地区的不同文件夹中都有多个重复的文件名,这是一个问题吗?即 xyz.png 也可能在 ca/payments 和 de/payments 中
图像不需要完整路径。仅使用名称(如果您直接添加图像)
cell.paymentImageView.image = UIImage(named: "x.png")!
如果您使用的是 .xcassets。使用图像集的名称而不是单个图像
cell.paymentImageView.image = UIImage(named: "<IMAGE_SET_NAME>")!
此崩溃是因为您尝试强制解包可选值。
UIImage(named: "logos/ca/payments/x.png")
是可选值。如果您的项目中不存在图片,则为 nil。
而且我们在获取图片时不需要输入路径,只需要图片名称和扩展文件,如UIImage(named: "x.png")
也cell.paymentImageView.image
可以接受nil图像。所以这一行只有 cell.paymentImageView.image = UIImage(named: "x.png")
就可以了。
希望对您有所帮助!