在 swift 的子文件夹中找不到图像?
can not find image in subfolder in swift?
我正在构建一个非常简单的循环查看图片的应用程序。
所有图片都存储在项目的子文件夹中:
这是 ViewController 中的代码:
@IBOutlet var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
var images = [UIImage]()
let items = Bundle.main.paths(forResourcesOfType: "jpg", inDirectory: "images")
for item in items {
let fileName = URL(string: item)?.lastPathComponent ?? "c1.jpg"
let image = UIImage(named: fileName)!
images.append(image)
}
imageView.image = UIImage.animatedImage(with: images, duration: Double(5*items.count))
}
}
这会在 let image = UIImage(named: fileName)!
行引发运行时错误
Fatal error: Unexpectedly found nil while unwrapping an Optional
value: file
fileName 的值是 "c1.jpg",听起来不错。
如果我的记忆还在,同样的代码在模拟器上运行,但在真实设备上出现运行时错误,现在它在两个模拟器上都停止运行了。不确定哪里出了问题?我可以看到 "images" 文件夹列在 "Build Phases" 中,所以我认为应该将图像复制到包中?:
尝试
let image = UIImage(named:"images/\(fileName)")!
或
let items = Bundle.main.urls(forResourcesWithExtension: "jpg", subdirectory: "images") ?? []
for item in items {
if let imageData = try? Data(contentsOf:item) {
let image = UIImage(data:imageData)!
images.append(image)
}
}
我正在构建一个非常简单的循环查看图片的应用程序。
所有图片都存储在项目的子文件夹中:
这是 ViewController 中的代码:
@IBOutlet var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
var images = [UIImage]()
let items = Bundle.main.paths(forResourcesOfType: "jpg", inDirectory: "images")
for item in items {
let fileName = URL(string: item)?.lastPathComponent ?? "c1.jpg"
let image = UIImage(named: fileName)!
images.append(image)
}
imageView.image = UIImage.animatedImage(with: images, duration: Double(5*items.count))
}
}
这会在 let image = UIImage(named: fileName)!
Fatal error: Unexpectedly found nil while unwrapping an Optional value: file
fileName 的值是 "c1.jpg",听起来不错。
如果我的记忆还在,同样的代码在模拟器上运行,但在真实设备上出现运行时错误,现在它在两个模拟器上都停止运行了。不确定哪里出了问题?我可以看到 "images" 文件夹列在 "Build Phases" 中,所以我认为应该将图像复制到包中?:
尝试
let image = UIImage(named:"images/\(fileName)")!
或
let items = Bundle.main.urls(forResourcesWithExtension: "jpg", subdirectory: "images") ?? []
for item in items {
if let imageData = try? Data(contentsOf:item) {
let image = UIImage(data:imageData)!
images.append(image)
}
}