2016-11-27 51 views
4

我在UIViewController中有多個UIButton實例,並且我想在按壓任何這些按鈕(一直向下)時執行一些操作,我不想在這裏不知道確切的名詞(強迫接觸也許?)。對UIButton上的3D Touch執行操作的最佳方式

所以當UIButton的壓力,我想通過振動給觸覺反饋,更改按鈕圖像源,並做一些其他的東西。然後,當壓力被釋放,我要恢復按鈕圖像源到正常狀態,並做一些更多的東西。

什麼是最簡單的方法是什麼?

我是否應該像我自己的自定義UIButton一樣,或有方法可以覆蓋3D按「按下」和「釋放」。

這是我的自定義的UIButton到目前爲止的代碼。我是否應該通過反覆試驗確定最大力量應該是多少?還有我怎麼改變圖像的在可能的最簡單的方法每個按鈕的來源?

import AudioToolbox 
import UIKit 

class customButton : UIButton { 
    override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { 
     for touch in touches { 
      print("% Touch pressure: \(touch.force/touch.maximumPossibleForce)"); 
      if touch.force > valueThatIMustFindOut { 
       AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate)) 
       // change image source 
       // call external function 
      } 
     } 
    } 

    override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { 
     print("Touches End") 
     // restore image source 
     // call external function 
    } 
} 

請注意,我是Swift新手,所以我想盡可能使用Xcode中的圖形界面來創建用戶界面。所以我想避免從代碼中創建UI。

回答

2

至於力觸摸 - 你需要檢測,如果它是可用的第一:

func is3dTouchAvailable(traitCollection: UITraitCollection) -> Bool { 
    return traitCollection.forceTouchCapability == UIForceTouchCapability.available 
} 

if(is3dTouchAvailable(traitCollection: self.view!.traitCollection)) { 
    //... 
} 

,然後在如touchesMoved這將作爲touch.forcetouch.maximumPossibleForce

func touchMoved(touch: UITouch, toPoint pos: CGPoint) { 
    let location = touch.location(in: self) 
    let node = self.atPoint(location) 

    //... 
    if is3dTouchEnabled { 
     bubble.setPressure(pressurePercent: touch.force/touch.maximumPossibleForce) 
    } else { 
     // ... 
    } 
} 

下面是一些代碼樣本的更詳細的例子: http://www.mikitamanko.com/blog/2017/02/01/swift-how-to-use-3d-touch-introduction/

這也是一個很好的做法,這種「反應力觸摸「,所以用戶將體驗觸摸:

let generator = UIImpactFeedbackGenerator(style: .heavy) 
generator.prepare() 

generator.impactOccurred() 

你可能想要看看這個帖子的細節: http://www.mikitamanko.com/blog/2017/01/29/haptic-feedback-with-uifeedbackgenerator/

相關問題