通过子视图移动正方形

时间:2017-05-31 14:24:30

标签: ios swift uiview uibezierpath uiswipegesturerecognizer

我是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")

    }

}

`

1 个答案:

答案 0 :(得分:0)

跟进我们的评论,你需要做两件事:添加@objc你的handleGesture()函数,以便它可以在选择器中使用,并确保你的选择器指定正确的签名,这是handleGesture(:),因为它只需要一个参数。