如果用户的手指每次在屏幕上移动时都将其存储在一个数组中,那么您可以很容易地做到这一点。我写了一些你可以遵循的代码。这很容易遵循和直截了当。
创建一个单视图应用程序并放置此代码并运行该应用程序并查看其结果。
import UIKit
class ViewController: UIViewController {
let numViewPerRow = 15
var cells = [String: UIView]()
override func viewDidLoad() {
super.viewDidLoad()
let width = view.frame.width / CGFloat(numViewPerRow)
let numViewPerColumn = Int(view.frame.height / width)
for j in 0...numViewPerColumn {
for i in 0...numViewPerRow {
let cellView = UIView()
cellView.backgroundColor = UIColor(red: .random(in: 0...1), green: .random(in: 0...1), blue: .random(in: 0...1), alpha: 1)
cellView.frame = CGRect(x: CGFloat(i) * width, y: CGFloat(j) * width, width: width, height: width)
cellView.layer.borderWidth = 0.5
cellView.layer.borderColor = UIColor.black.cgColor
view.addSubview(cellView)
let key = "\(i)|\(j)"
cells[key] = cellView
}
}
view.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(handlePan)))
}
var selectedCell: UIView?
@objc func handlePan(gesture: UIPanGestureRecognizer) {
let location = gesture.location(in: view)
let width = view.frame.width / CGFloat(numViewPerRow)
let i = Int(location.x / width)
let j = Int(location.y / width)
print(i, j)
let key = "\(i)|\(j)"
guard let cellView = cells[key] else { return }
if selectedCell != cellView {
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
self.selectedCell?.layer.transform = CATransform3DIdentity
}, completion: nil)
}
selectedCell = cellView
view.bringSubviewToFront(cellView)
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
cellView.layer.transform = CATransform3DMakeScale(3, 3, 3)
}, completion: nil)
if gesture.state == .ended {
UIView.animate(withDuration: 0.5, delay: 0.25, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.5, options: .curveEaseOut, animations: {
cellView.layer.transform = CATransform3DIdentity
}, completion: { (_) in
})
}
}
}