编辑: 我能够以某种方式更改代码,程序不会再崩溃。但是,代码仍然只有一个小问题:
正如您在我的控制台输出中所看到的,origin2的坐标与原点1的坐标不同。
origin1:(268.0,241.0)origin2:(116.0,323.0)发件人查看中心: 可选((146.5,397.0))
所以我需要从viewDidLoad()获取imageOrigin1值并使用它们im func handlePan(sender:UIPanGestureRecognizer)。 我只是不知道该怎么做......
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var image: UIImageView!
@IBOutlet weak var correctField: UIImageView!
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidLoad() {
super.viewDidLoad()
let imageOrigin1 = image.frame.origin
print("origin1: \(imageOrigin1)")
}
@IBAction func handlePan(sender:UIPanGestureRecognizer) {
let imageOrigin2 = image.frame.origin
let translation = sender.translationInView(self.view)
if let view = sender.view {
view.center = CGPoint(x:view.center.x + translation.x,
y:view.center.y + translation.y)
}
if sender.state == UIGestureRecognizerState.Ended {
if correctField.frame.contains(sender.view!.center){
print("Correct")
sender.setTranslation(CGPointZero, inView: self.view)
} else{
print("origin2: \(imageOrigin2)")
print("sender view center: \(sender.view?.center)")
//sender.view?.center = imageOrigin
}
}
}
}
答案 0 :(得分:0)
我自己解决了这个问题,添加了一个新类并通过set和get方法传递变量:
CLASS:
import UIKit
class Origin {
var positionOrigin: CGPoint!
func setImageOrigin(Image: UIImageView) {
positionOrigin = Image.center
}
func getImageOrigin() -> CGPoint {
return positionOrigin
}
}
查看控制器:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var correctField: UIImageView!
@IBOutlet weak var image: UIImageView!
var imageOrigin = Origin()
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidLoad() {
super.viewDidLoad()
imageOrigin.setImageOrigin(image)
}
@IBAction func handlePan(sender:UIPanGestureRecognizer) {
let translation = sender.translationInView(self.view)
if let view = sender.view {
view.center = CGPoint(x:view.center.x + translation.x,
y:view.center.y + translation.y)
sender.setTranslation(CGPointZero, inView: self.view)
}
if sender.state == UIGestureRecognizerState.Ended {
if correctField.frame.contains(sender.view!.center){
print("Correct")
} else{
image.center = imageOrigin.getImageOrigin()
}
}
}
}