gpt4 book ai didi

swift - 让可拖动的 UIImage 移回原点位置

转载 作者:行者123 更新时间:2023-11-28 08:31:07 27 4
gpt4 key购买 nike

编辑:我能够以某种方式更改代码,使程序不再崩溃。但是,代码运行只剩下一个小问题:

正如您在我的控制台输出中看到的那样,origin2 的坐标与 origin 1 中的坐标不同。

origin1: (268.0, 241.0) origin2: (116.0, 323.0) sender view center: Optional((146.5, 397.0))

所以我需要从 viewDidLoad() 获取 imageOrigin1-values 并在 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
}
}
}
}

最佳答案

我自己解决了这个问题,添加了一个新类并通过 set 和 get 方法传递变量:

类(class):

import UIKit

class Origin {

var positionOrigin: CGPoint!

func setImageOrigin(Image: UIImageView) {
positionOrigin = Image.center
}

func getImageOrigin() -> CGPoint {
return positionOrigin
}
}

查看 Controller :

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()

}
}
}
}

关于swift - 让可拖动的 UIImage 移回原点位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38866900/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com