Swift:如何更改带有上一个和下一个按钮的UIImage



我有一个显示当前图像的功能和两个按钮(上一个和下一个(来显示上一个图像或下一个图像。但是我的代码有一些错误。请帮忙。Ty.

import UIKit
class ViewController: UIViewController {

func showImage() {
if count < photoCollection.count {
if let images = photoCollection[count] as? Dictionary<UIImage, String> {
photo.image = images.keys.first
Text.text = images.values.first
}
} else {
debugPrint("Failed!")
}
}

}

字典不是适合该作业的工具,但如果必须使用字典,则至少应确保密钥比UIImage对用户更友好。如果定义一个类型来保存图像和文本,则可以使用一个整数在字典中键入以访问所需的值。

class ViewController1: UIViewController {
struct Photo {
let image: UIImage?
let text: String
}
var count = 0
var photoCollection: [Int: Photo] = [
0: Photo(image: UIImage(named: "P1"), text: "City Tavern Bathroom"),
1: Photo(image: UIImage(named: "P2"), text: "Shafer Trail, Island in the Sky District"),
2: Photo(image: UIImage(named: "P3"), text: "Rivers Bend Group Campground"),
3: Photo(image: UIImage(named: "P4"), text: "Delta at Lake Mead"),
4: Photo(image: UIImage(named: "P5"), text: "Deer between Sequoias"),
5: Photo(image: UIImage(named: "P6"), text: "Arlington House, The Robert E. Lee Memorial"),
6: Photo(image: UIImage(named: "P7"), text: "Brink of the Lower Falls of the Yellowstone River"),
7: Photo(image: UIImage(named: "P8"), text: "Garage Exterior"),
8: Photo(image: UIImage(named: "P9"), text: "DSCF1199"),
9: Photo(image: UIImage(named: "P10"), text: "The Bi-national Formation"),
]
func showImage() {
guard let item = photoCollection[count] else { return }
photo.image = item.image
Text.text = item.text
}
}

我会使用一组字典:

import UIKit
class ViewController: UIViewController {
var count = 0
var photoCollection: [[String:Any]] = [
["image": UIImage(named: "P1")!, "text": "City Tavern Bathroom"],
// 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()
}
}

当无法后退或前进时,您也可以禁用按钮。

最新更新