gpt4 book ai didi

ios - 通过触摸来回移动物体

转载 作者:行者123 更新时间:2023-11-30 13:39:59 26 4
gpt4 key购买 nike

我需要通过用户触摸在屏幕上左右移动对象。我已经使对象随着用户触摸而移动,但我想让对象或图像只能向右或向左移动。我应该使用什么代码来执行此操作?这是我现在拥有的。

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.
}


}

最佳答案

这应该有效。您可以更改 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.
}


}

我确信有更好的方法,但我仍然是初学者,所以......

关于ios - 通过触摸来回移动物体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35690256/

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