Swift: 如何将 UIImage 及其描述存储在一个集合中?

Swift: How to store UIImage and its description in a collection?

我需要将它们存储在一个集合中。然后我将有两个按钮“上一个”和“下一个”。如果我们到达集合的末尾,它应该从头开始或跳到末尾。

class ViewController: UIViewController {


var photoCollection: [[String:Any]] = [
        ["image": UIImage(named: "Sea house")!, "text": "sea house"]
        // Other photos
    ]



@IBOutlet weak var photo: UIImageView!
@IBOutlet weak var Text: UILabel!



func showImage() {
    
    photo.image = photoCollection[count]["image"] as! UIImage
    Text.text = photoCollection[count]["text"] as! String
    }




@IBAction func Previous(_ sender: UIButton)
{
    guard count > 0 else {return}
            count -= 1
            showImage()
    
}


@IBAction func Next(_ sender: UIButton) {
   
    guard count < photoCollection.count - 1 else {return}
            count += 1
            showImage()
        }
    



override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
}

}

请帮忙调试代码。

谢谢!

您需要更新这些方法

@IBAction func Previous(_ sender: UIButton) {
    count = count > 0 ? count - 1 : photoCollection.count - 1
    showImage()
}
    
@IBAction func Next(_ sender: UIButton) {
    count = count < photoCollection.count - 1 ? count + 1 : 0
    showImage()
}

这会让你无限循环。

编辑// 崩溃修复

photoCollection 中你使用了 UImage(named: "nameOfImage")!,这个初始化器可以 return nil 如果它找不到具有该名称的图像,并且当你使用强制解包你的应用程序时因该错误而崩溃。 首先不要使用强制解包,这是不好的做法,在极少数情况下使用。

怎么做才更安全?

将您的 collection 更改为 -- >

var photoCollection: [[String:Any?]] = [
                                ["image": UIImage(named: "P1"), "text": "City Tavern Bathroom"],
                                ["image": UIImage(named: "P2"), "text": "Shafer Trail, Island in the Sky District"],
                                ["image": UIImage(named: "P3"), "text": "Rivers Bend Group Campground"],
                                ["image": UIImage(named: "P4"), "text": "Delta at Lake Mead"],
                                ["image": UIImage(named: "P5"), "text": "Deer between Sequoias"],
                                ["image": UIImage(named: "P6"), "text": "Arlington House, The Robert E. Lee Memorial"],
                                ["image": UIImage(named: "P7"), "text": "Brink of the Lower Falls of the Yellowstone River"],
                                ["image": UIImage(named: "P8"), "text": "Garage Exterior"],
                                ["image": UIImage(named: "P9"), "text": "DSCF1199"],
                                ["image": UIImage(named: "P10"), "text": "The Bi-national Formation"] ] 

然后把你的showImage()方法改成这个

 func showImage() {
        guard let image = photoCollection[count]["image"] as? UIImage,
              let description = photoCollection[count]["text"] as? String else {
            return
        }
        photo.image = image
        Text.text = description
    }

知道您的应用程序不会崩溃,即使找不到具有某个名称的图像。 但是您需要检查所有图像及其名称以确保应用程序正常工作。