点击手势由以下功能触发;
@objc func handleTapGR(tapGR: UITapGestureRecognizer) {
let tapLocation = tapGR.location(in: nil)
let moveNext = tapLocation.x > frame.width / 2 ? true : false
moveNext ? userCards.nextImage() : userCards.previousImage()
}
UserCardViewModel:
...
var imageIndex: Int = 0 { didSet{ imageIndexObserver?(imageIndex, userImages[imageIndex]) } }
var imageIndexObserver: ((Int, UIImage) -> () )?
mutating func nextImage() {
imageIndex = imageIndex + 1 >= userImages.count ? 0 : imageIndex + 1
}
mutating func previousImage() {
imageIndex = imageIndex - 1 < 0 ? userImages.count - 1 : imageIndex - 1
}
更改索引时需要触发相关的关闭。 下面的对象处于相关视图中。
var userCards: UserCardViewModel! {
didSet{
userCards.imageIndexObserver = { index, image in
self.showingImage.image = self.userCards.userImages[index]
print(index)
}
}
}
在前两次点击时我无法在index语句上方打印。当我在图像上按右侧时(相关数组数为2)
我正在从相关的ViewController进行初始化
convenience init(userCards: UserCardViewModel) {
self.init(frame: .zero)
self.userCards = userCards
configure()
}
答案 0 :(得分:0)
我已添加手势。点击右侧索引时,计数将增加(左侧将减少),一旦达到数组计数,则将从0开始重新计数。
class ViewController: UIViewController {
var userCards = UserCardViewModel() {
didSet{
userCards.imageIndexObserver = { index, image in
//self.showingImage.image = self.userCards.userImages[index]
print(index) //<------- Here you will get index
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
let img1 = UIImage(systemName: "arrow.up.right.video")
let img2 = UIImage(systemName: "arrow.up.right.video")
let img3 = UIImage(systemName: "arrow.up.right.video")
userCards.userImages = [img1!,img2!,img3!]
let tap = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:)))
self.view.addGestureRecognizer(tap)
}
@objc func handleTap(_ tapGR: UITapGestureRecognizer) {
let tapLocation = tapGR.location(in: nil)
let moveNext = tapLocation.x > self.view.frame.width / 2 ? true : false
moveNext ? userCards.nextImage() : userCards.previousImage()
}
}
这是Model类
struct UserCardViewModel {
var userImages : [UIImage] = []
var imageIndex: Int = 0 {
didSet {
imageIndexObserver?(imageIndex, userImages[imageIndex])
} }
var imageIndexObserver: ((Int, UIImage) -> () )?
mutating func nextImage() {
imageIndex = imageIndex + 1 >= userImages.count ? 0 : imageIndex + 1
}
mutating func previousImage() {
imageIndex = imageIndex - 1 < 0 ? userImages.count - 1 : imageIndex - 1
}
}
最初imageIndex
是0
1)在开始时,点击右侧的imageIndex
将变为1
2)在开始时,点击左侧的imageIndex
将变为(yourArray.count-1)
从here下载演示