我需要在用户触摸屏幕上将对象左右移动。我已经通过用户触摸使对象移动但我想要使对象或图像只能向右或向左移动。我应该使用什么代码来执行此操作?这就是我现在所拥有的。
import UIKit
class ViewController: UIViewController {
@IBOutlet var Person: UIImageView!
var location = CGPoint (x: 0, y: 0)
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
let touch : UITouch! = touches.first! as UITouch
location = touch!.locationInView(self.view)
Person.center = location
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
let touch : UITouch! = touches.first! as UITouch
location = touch!.locationInView(self.view)
Person.center = location
}
override func viewDidLoad() {
super.viewDidLoad()
Person.center = CGPointMake(160, 330)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
答案 0 :(得分:0)
这应该有效。您可以更改y以更改您希望UIImageView始终保持打开的方式,但请确保两者相同!至少,这应该给你一个想法或让你朝着正确的方向。
import UIKit
class ViewController: UIViewController {
@IBOutlet var Person: UIImageView!
var location = CGPoint(x: 0, y: 0)
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
let touch : UITouch! = touches.first! as UITouch
location = touch!.locationInView(self.view)
let point = location.x
Person.center = CGPoint(x: point, y: 160) // change 160 to set vertical height you desire
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
let touch : UITouch! = touches.first! as UITouch
location = touch!.locationInView(self.view)
let point = location.x
Person.center = CGPoint(x: point, y: 160) // change 160 to set vertical height you desire
}
override func viewDidLoad() {
super.viewDidLoad()
Person.center = CGPointMake(160, 330)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
我相信有更好的方法,但我仍然是初学者,所以......