当 UIPanGesture 上的状态为 .ended 时遍历数组
Posted
技术标签:
【中文标题】当 UIPanGesture 上的状态为 .ended 时遍历数组【英文标题】:Loop through array when state on UIPanGesture is .ended 【发布时间】:2019-03-13 21:39:33 【问题描述】:我想知道如何循环遍历数组并在识别器.state .ended 之后更改名称。当我使用 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
如果我把它放在完整的动画上,它会循环一个数组并向我显示最后一个项目。
【问题讨论】:
你在哪里使用forEach
?
"当我使用 forEach 方法时,它只显示数组中的最后一项。"嗯,这听起来很奇怪。你对 forEach 的使用是什么样的?
【参考方案1】:
您的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
【讨论】:
以上是关于当 UIPanGesture 上的状态为 .ended 时遍历数组的主要内容,如果未能解决你的问题,请参考以下文章
UIPanGestureRecognizer 未调用结束状态
让 UIPanGesture 和 UISwipeGesture 朝着同一个方向一起工作
使用自动布局约束时,UIView 无法通过 UIpangesture 顺利拖动