【发布时间】:2020-03-24 09:43:22
【问题描述】:
如果调用该函数,我下面的快速代码应该添加一个图像视图。然后当按下它应该四处移动。现在第一次按下按钮时,imageview 不起作用,但如果函数被调用两次,第一个 imageview 会移动。如果 func 被调用 3 次,第一个和第二个图像视图会移动,但第三个不会。当图像视图被放置在屏幕上时,我希望它立即移动
import UIKit
class ViewController: UIViewController {
var myArray = [UIImageView]()
var bt = UIButton()
var count : Int = 0
var pgGesture = UIPanGestureRecognizer()
var ht = -90
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(bt)
bt.backgroundColor = UIColor.systemOrange
bt.frame = CGRect(x: view.center.x - 80, y: view.center.y , width: 50, height: 50)
bt.addTarget(self, action: #selector(add), for: .touchUpInside)
}
@objc func add() {
pgGesture = UIPanGestureRecognizer(target: self, action: #selector(ViewController.pgGestureMethod(_:)))
for index in myArray.indices {
myArray[index].isUserInteractionEnabled = true
myArray[index].addGestureRecognizer(pgGesture)
myArray[index].tag = index
}
myArray.insert(UIImageView(), at: count)
myArray[count].frame = CGRect(x: view.center.x - 0, y: view.center.y + CGFloat(ht), width: 50, height: 30)
myArray.forEach({
$0.backgroundColor = UIColor.systemTeal
self.view.addSubview($0)
})
count += 1
ht += 50
}
@objc func pgGestureMethod(_ sender: UIPanGestureRecognizer){
self.view.bringSubviewToFront(sender.view!)
let tranistioon = sender.translation(in: self.view)
sender.view!.center = CGPoint(x: sender.view!.center.x + tranistioon.x, y: sender.view!.center.y + tranistioon.y)
sender.setTranslation(CGPoint.zero,in: self.view)
}
}
【问题讨论】:
-
不确定这是否能解决您的问题,但无论如何您应该将以下行
pgGesture = UIPanGestureRecognizer(target: self, action: #selector(ViewController.pgGestureMethod(_:)))放在 ViewdidLoad 中,而不是放在 add() 函数中。 -
同样的事情正在发生,没有任何变化。
标签: arrays swift for-loop indexing uipangesturerecognizer