|
|||||
|
対象: View Controllerを3D Touchに対応させる(Swift)アプリを3D Touchに対応させるにはどうしたらよいだろうか?例えば、UIViewControllerに3D Touch機能を実装するには、ViewControllerでUIViewControllerPreviewingDelegateを継承し、registerForPreviewingWithDelegateメソッドで自分自身を登録する。
class ViewController: UIViewController, UIViewControllerPreviewingDelegate {
registerForPreviewingWithDelegateメソッドを呼ぶ前には、traitCollection.forceTouchCapabilityを調べて、端末が3D Touchに対応しているかどうか確認する。
if traitCollection.forceTouchCapability == UIForceTouchCapability.Available {
print("3D Touch available")
registerForPreviewingWithDelegate(self, sourceView: view)
}
ViewControllerでUIViewControllerPreviewingDelegateを継承したら、previewingContext(_:viewControllerForLocation:)メソッドとpreviewingContext(_:commitViewController:)は必須なので実装する。
func previewingContext(previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
// プレビューで表示するUIViewControllerのサブクラスを生成
return viewController
}
func previewingContext(previewingContext: UIViewControllerPreviewing, commitViewController viewControllerToCommit: UIViewController) {
// 処理
}
これら2つのメソッドを実装する前は、ViewControllerクラスを宣言しているところが以下のようなエラーになるが、実装すれば消えるので気にしなくても良い。 Type 'ViewController' does not conform to protocol 'UIViewControllerPreviewingDelegate' previewingContext(_:viewControllerForLocation:)メソッドはUIViewController(のサブクラス)を返さなければならない。ここでは動作確認のためにUIAlertControllerを返しておく。また、標準のメールアプリ等でメールをプレビューしたときの、「ポキッ」というフィードバックは一連のAPIには含まれない?ようなので、別途バイブレーションを作動させてみる。
import UIKit
import AVFoundation
class ViewController: UIViewController, UIViewControllerPreviewingDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
if traitCollection.forceTouchCapability == UIForceTouchCapability.Available {
print("3D Touch available")
registerForPreviewingWithDelegate(self, sourceView: view)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func previewingContext(previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
print("viewControllerForLocation")
AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate))
// UIViewControllerのサブクラスであれば良さそうなのでUIAlertControllerで代用
let alert = UIAlertController(title: "3D Touch", message: "Pressed", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) { action -> Void in print("OKが押されました。") })
return alert
}
func previewingContext(previewingContext: UIViewControllerPreviewing, commitViewController viewControllerToCommit: UIViewController) {
print("viewControllerToCommit")
}
}
因みに、3D Touchは設定 > 一般 > アクセシビリティ > 3D TouchでOffにすることができる。 (2015/10/12)
Copyright© 2004-2019 モバイル開発系(K) All rights reserved.
[Home]
|
|||||