作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想知道如何循环遍历数组并在 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/
我是一名优秀的程序员,十分优秀!