0
我是Swift中的新手。 我試圖用swift 3中的手勢識別器來移動一個正方形,但是我不知道該怎麼做。我想用UISwipeGestureRecognizer來做它,因爲稍後它將用作頭部的方塊蛇:)在子視圖中移動正方形
這是代碼:
@IBAction func Start(_ sender: UIButton) {
self.StartTheGame()
}
@IBOutlet var StartGame: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// set container frame and add to the screen
self.container.frame = CGRect(x: 10, y: 20, width: 390, height: 740)
self.view.addSubview(container)
self.container.backgroundColor = UIColor.black
self.container.addSubview(StartGame)
let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(handleGesture))
swipeLeft.direction = .left
self.view.addGestureRecognizer(swipeLeft)
let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(handleGesture))
swipeRight.direction = .right
self.view.addGestureRecognizer(swipeRight)
let swipeUp = UISwipeGestureRecognizer(target: self, action: #selector(handleGesture))
swipeUp.direction = .up
self.view.addGestureRecognizer(swipeUp)
let swipeDown = UISwipeGestureRecognizer(target: self, action: #selector(handleGesture))
swipeDown.direction = .down
self.view.addGestureRecognizer(swipeDown)
}
func handleGesture(gesture: UISwipeGestureRecognizer) -> Void {
if gesture.direction == UISwipeGestureRecognizerDirection.right {
print("Swipe Right")
}
else if gesture.direction == UISwipeGestureRecognizerDirection.left {
print("Swipe Left")
}
else if gesture.direction == UISwipeGestureRecognizerDirection.up {
print("Swipe Up")
}
else if gesture.direction == UISwipeGestureRecognizerDirection.down {
print("Swipe Down")
}
}
func StartTheGame() {
self.StartGame!.isHidden = true
let rect = Draw(frame: CGRect(origin: CGPoint(x: 170, y: 300), size: CGSize(width: 40, height: 40)))
self.container.addSubview(rect)
}
這在班上是平局:
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ rect: CGRect) {
let h = rect.height
let w = rect.width
UIColor.yellow.set()
let rect = CGRect(x: (w * 0.25),y: (h * 0.25),width: (w * 0.5),height: (h * 0.5))
let bpath:UIBezierPath = UIBezierPath(rect: rect)
bpath.fill()
//UIBezierPath(rect: rect).fill()
NSLog("drawRect has updated the view")
}
}
`
你想要一個'UIPanGestureRecognizer',而不是'UISwipeGestureRecognizer',因爲前者會跟蹤連續的手指移動,而後者僅用於快速向一個方向滑動。 – NRitH
'Draw'(幾乎總是)動詞,因此是一個類的_terrible_名稱。你不想讓手勢附加到被移動的視圖上,而不是容器視圖上? – NRitH
但是我使用了UISWipeGestureRecognizer,因爲我想快速刷一下,改變蛇的方向(蛇遊戲 - 向上,向下,向左,向右移動,只需在屏幕上一觸即可),這就是爲什麼我使用Swipe。 – felix89