2016-09-30 92 views
-2
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套件的信息,但由於它只包含摘錄,我不理解響應。有人可以提供最簡單的答案,涉及我的實際示例代碼?如何觸摸移動按鈕?

謝謝。

編輯:我希望能夠觸摸圖像當前的按鈕,而不是按鈕將在哪裏結束。

+0

你爲什麼要用透明度來破解這個?你試圖解決的實際問題是什麼?可能有更好的(適當的)方法來解決它。 – brandonscript

+0

我剛剛在Stack上看到它,並提出了評論和評論建議。如果你真的推薦它,那麼我會改變整個問題。 – ludluck

+0

我在說我不明白你想解決的問題是什麼。首先重新說明你的問題,這很清楚你想要完成什麼。 – brandonscript

回答

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() 
    } 
} 

並訪問按鈕的當前位置,你可以使用presentationLayerframe,修改activate()方法是這樣的:

func activate() { 
    if let presentationLayer = button.layer.presentationLayer() { 
     print(presentationLayer.frame.midX) 
    } else { 
     print(button.center.x) 
    } 
} 

*從iOS 10開始,不需要使用touchesBegan和hitTest,因爲.AllowUserInteraction足以讓您在動畫過程中以當前狀態點擊它。

+0

也許我沒有具體的問題,但問題是,按鈕交互只發生在按鈕的位置,而不是當前按鈕圖像的位置。 – ludluck

+0

@ludluck請看我更新的答案。 –

+0

我完全按照你的說法做了,而且它的功能非常好,謝謝你。但是,你的*評論意味着什麼?當iOS 10發佈時,我只需要使用原始解決方案?這會容易得多!編輯:等一下,它已經發布了。 – ludluck