如何触摸移动按钮?

时间:2016-09-30 23:08:58

标签: swift

class ViewController: UIViewController {

    let manImage = UIImage(named: "man.png")

    let button = UIButton()

    override func viewDidLoad() {
        super.viewDidLoad()

        button.setBackgroundImage(manImage, forState: .Normal)
        button.addTarget(self, action: "activate", forControlEvents: .TouchUpInside)
        button.translatesAutoresizingMaskIntoConstraints = false
        self.view.addSubview(button)
        self.view.addConstraint(NSLayoutConstraint(
            item: button,
            attribute: .Leading,
            relatedBy: .Equal,
            toItem: view,
            attribute: .Leading,
            multiplier: 1,
            constant: 0))
        self.view.addConstraint(NSLayoutConstraint(
            item: button,
            attribute: .CenterY,
            relatedBy: .Equal,
            toItem: view,
            attribute: .CenterY,
            multiplier: 1,
            constant: 0))

        startAnimating()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func startAnimating() {
        UIView.animateWithDuration(10, delay: 0, options: .CurveLinear, animations: {
            self.button.frame.origin.x = self.button.frame.origin.x - 150}, completion: nil)
    }

    func activate() {
        print(button.center.x)
    }

}

如何在移动按钮时触摸按钮?我读过有关更新命中测试和使用Quartz工具包的内容,但我不理解响应,因为它只包含摘录。有人可以提供涉及我的实际示例代码的最简单的答案吗?

谢谢。

编辑:我希望能够触摸当前图像的按钮,而不是按钮最终的位置。

1 个答案:

答案 0 :(得分:2)

您需要添加.AllowUserInteraction作为动画选项之一。

替换此行

UIView.animateWithDuration(10, delay: 0, options: .CurveLinear, animations: {

有了这个

UIView.animateWithDuration(10, delay: 0, options: [.CurveLinear, .AllowUserInteraction], animations: {

这将让您点击动画结尾处的按钮。

要在动画期间点击当前状态的按钮,您需要覆盖touchesBegan方法并使用按钮的presentationLayer hitTest触摸位置。
将此代码添加到您的班级:

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    guard let touch = touches.first else {
        return
    }
    let touchLocation = touch.locationInView(self.view)
    if self.button.layer.presentationLayer()?.hitTest(touchLocation) != nil {
        activate()
    }
}

要访问按钮的当前位置,您可以使用presentationLayer的{​​{1}},修改frame方法,如下所示:

activate()

*从iOS 10开始,似乎不需要使用touchesBegan和hitTest,因为func activate() { if let presentationLayer = button.layer.presentationLayer() { print(presentationLayer.frame.midX) } else { print(button.center.x) } } 足以让你在动画期间点击它的当前状态。