将图像数组获取到集合视图
getting an array of images to collection view
我正在尝试获取我的文档目录中的图像数组,以便在 UICollectionView
中显示 我在获取实际图像数组时遇到了问题。我花了一些时间尝试 google 这个,但大多数人似乎是从应用程序包中获取他们的图像。我需要我的图像来自文件。
这是我尝试使用的代码:
func getImageArray() {
let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
if let dirPath = paths.first
{
let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent("Images")
let image = UIImage(contentsOfFile: imageURL.path)
imageArray.append(image)
print(imageURL)
}
}
我对 swift 很陌生,所以答案可能很明显。有人可以指出我正确的方向或告诉我我做错了什么吗
您可以尝试读取目录内容,然后单独循环从 url 创建图像
do {
let allImages = URL(fileURLWithPath: dirPath).appendingPathComponent("Images")
let directoryContents = try FileManager.default.contentsOfDirectory(atPath: allImages.path)
for con in directoryContents {
let img = URL(fileURLWithPath:allImages).appendingPathComponent(con)
let image = UIImage(contentsOfFile: img.path)
imageArray.append(image)
}
}
catch {
print(error)
}
我正在尝试获取我的文档目录中的图像数组,以便在 UICollectionView
中显示 我在获取实际图像数组时遇到了问题。我花了一些时间尝试 google 这个,但大多数人似乎是从应用程序包中获取他们的图像。我需要我的图像来自文件。
这是我尝试使用的代码:
func getImageArray() {
let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
if let dirPath = paths.first
{
let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent("Images")
let image = UIImage(contentsOfFile: imageURL.path)
imageArray.append(image)
print(imageURL)
}
}
我对 swift 很陌生,所以答案可能很明显。有人可以指出我正确的方向或告诉我我做错了什么吗
您可以尝试读取目录内容,然后单独循环从 url 创建图像
do {
let allImages = URL(fileURLWithPath: dirPath).appendingPathComponent("Images")
let directoryContents = try FileManager.default.contentsOfDirectory(atPath: allImages.path)
for con in directoryContents {
let img = URL(fileURLWithPath:allImages).appendingPathComponent(con)
let image = UIImage(contentsOfFile: img.path)
imageArray.append(image)
}
}
catch {
print(error)
}