gpt4 book ai didi

arrays - 当 UIPanGesture 上的状态为 .ending 时循环遍历数组

转载 作者:行者123 更新时间:2023-11-30 10:48:41 24 4
gpt4 key购买 nike

我想知道如何循环遍历数组并在 recognizer.state .ending 之后更改名称。当我使用 forEach 方法时,它仅显示数组中的最后一项。数组:

let persons = [
Name(name: "Theo", imageName: "theoPhoto"),
Name(name: "Matt", imageName: "mattPhoto"),
Name(name: "Tom", imageName: "tomPhoto")
]

UIPanGestureRecognizer:

@IBAction func handleCard(recognizer: UIPanGestureRecognizer) {        

guard let card = recognizer.view else { return }
switch recognizer.state {
case .began:
initialCGRect = card.frame
case .changed:
handleChanged(recognizer, card)
case .ended:
handleEnded(recognizer, card)
default:
return
}
}

fileprivate func handleChanged(_ recognizer: UIPanGestureRecognizer, _ card: UIView) {
let panning = recognizer.translation(in: view)
let degrees : CGFloat = panning.x / 20
let angle = degrees * .pi / 180

let rotationTransformation = CGAffineTransform(rotationAngle: angle)
card.transform = rotationTransformation.translatedBy(x: panning.x, y: panning.y)
}

fileprivate func handleEnded(_ recognizer: UIPanGestureRecognizer, _ card: UIView) {

let transitionDirection: CGFloat = recognizer.translation(in: view).x > 0 ? 1 : -1
let shuldDismissCard = abs(recognizer.translation(in: view).x) > treshold

UIView.animate(withDuration: 1, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
if shuldDismissCard {
card.frame = CGRect(x: 600 * transitionDirection, y: 0, width: card.frame.width, height: card.frame.height)
} else {
card.transform = CGAffineTransform.identity
}

}) { (_) in
// Complete animation, bringing card back
card.transform = CGAffineTransform.identity
}
}

forEach 方法:

func setupCards() {        
persons.forEach { (Person) in
cardView.image = UIImage(named: Person.imageName)
cardLabel.text = Person.name
}
}

如果我把它放在完整的动画上,它会循环遍历一个数组并显示最后一个项目。

最佳答案

您的setupCards()方法是错误的。它将始终显示最后一项,因为您只更新一个 cardView。另外,不要在循环闭包中使用 Person 类名。您应该保存一个 CardView 数组,并相应地更改数据。

func setupCards() {        
var i = 0
persons.forEach { (p) in
let cardView = self.cards[i]
cardView.image = UIImage(named: p.imageName)
cardView.cardLabel.text = p.name
i += 1
}
}

关于arrays - 当 UIPanGesture 上的状态为 .ending 时循环遍历数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55151614/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com