我需要將這些存盤在一個集合中。然后我將有兩個按鈕“上一個”和“下一個”。如果我們到達集合的結尾,它應該從頭開始或跳到結尾。
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.
}
}
請幫忙除錯代碼。
謝謝!
uj5u.com熱心網友回復:
您需要更新這些方法
@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")! 內部,如果找不到具有該名稱的影像,則此初始化程式可以回傳 nil,并且當您使用強制解包時,應用程式會因該錯誤而崩潰。首先不要使用強制解包,這是不好的做法,它在一些罕見的情況下使用。
那怎么做比較安全呢?
將您的收藏更改為此-->
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
}
知道即使找不到帶有某個名稱的影像,您的應用程式也不會崩潰。但是您需要檢查所有影像及其名稱以確保應用程式正常作業。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/370238.html
