隨着iPhone 6s 和 iPhone 6s Plus 的發佈,蘋果開始添加了一種全新的觸控方式——3D Touch。最近幾天簡單地研究了一下,跟你們分享一下個人一些經驗。html
當你重按應用的圖標時,會彈出相似這樣的小菜單(以微信爲例): ios
添加這樣的快捷菜單主要有 靜態 和 動態 兩種方法: ####靜態方法 參看 UIApplicationShortcutItems-蘋果官方文檔git
能夠看到 UIApplicationShortcutItemTitle
和 UIApplicationShortcutItemType
這兩個變量是必須的。github
咱們在項目的 info.plist
文件中添加以下信息: 數組
運行結果: 微信
####動態方法 動態方法是在項目中添加代碼:app
UIApplicationShortcutItem *item1 = [[UIApplicationShortcutItem alloc] initWithType:@"one" localizedTitle:@"Title One" localizedSubtitle:@"Sub one" icon:[UIApplicationShortcutIcon iconWithType:UIApplicationShortcutIconTypePlay] userInfo:nil];
UIApplicationShortcutItem *item2 = [[UIApplicationShortcutItem alloc] initWithType:@"two" localizedTitle:@"Title Two" localizedSubtitle:@"Sub two" icon:[UIApplicationShortcutIcon iconWithType:UIApplicationShortcutIconTypeHome] userInfo:nil];
[UIApplication sharedApplication].shortcutItems = @[item1, item2];
複製代碼
當該段代碼在程序中被執行過一次後纔會被添加到主屏幕的 ShortcutItems
菜單中。 運行結果:dom
注意: ShortcutItems 會優先加載靜態方法添加的,而後加載動態方法添加的,而且同時只能擁有最多4個ShortcutItems。測試
####選擇 ShortcutItem 後的回調 在 AppDelegate
根據 shortcutItem.type
判斷回調方法:ui
- (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler {
if ([shortcutItem.type isEqualToString:@"one"]) {
NSLog(@"Choose One");
MyViewController *vc = [[MyViewController alloc] init];
vc.title = @"One";
vc.view.backgroundColor = [UIColor whiteColor];
[self.window.rootViewController showViewController:vc sender:nil];
} else if ([shortcutItem.type isEqualToString:@"two"]) {
NSLog(@"Choose Two");
MyViewController *vc = [[MyViewController alloc] init];
vc.title = @"Two";
vc.view.backgroundColor = [UIColor orangeColor];
[self.window.rootViewController showViewController:vc sender:nil];
}
}
複製代碼
在9.0後 UITouch
新增這樣兩個屬性:
咱們建立一個繼承於 UIView
的自定義View,這裏咱們首先要判斷一下設備是否支持3D Touch:
- (BOOL)check3DTouch {
if (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable) {
return YES;
} else {
return NO;
}
}
複製代碼
而後在 touchesMoved
中調用方法:
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
if ([self check3DTouch]) {
UITouch *touch = [touches anyObject];
self.backgroundColor = [UIColor colorWithRed:touch.force / touch.maximumPossibleForce green:0.0f blue:0.0f alpha:1.0f];
} else {
NSLog(@"CAN NOT USE 3D TOUCH!");
}
}
複製代碼
這樣咱們我建立了一個能夠根據按壓力度改變顏色的View。
####Peek和Pop: Peek是指重按一下後出現的預覽,Pop是在Peek後進一步按壓後進入預覽的視圖控制器。 首先遵循代理 <UIViewControllerPreviewingDelegate>
而後監測設備是否支持3D Touch,若支持則對須要響應Peek操做的視圖進行註冊:
- (void)check3DTouch {
if (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable) {
[self registerForPreviewingWithDelegate:self sourceView:_label];
}
}
複製代碼
Peek的代理方法
- (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location {
MyViewController *vc = [[MyViewController alloc] init];
vc.title = @"Hello";
vc.view.backgroundColor = [UIColor cyanColor];
return vc;
}
複製代碼
其實就是返回一個視圖控制器實例,可是看網上說這個方法會被屢次調用,我實際測試有時會調用屢次,有時只調用一次,仍是不太清楚具體調用狀況,有知道的朋友歡迎交流一下。爲了保險起見,仍是建議寫成下面的形式:
- (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location {
if ([self.presentedViewController isKindOfClass:[MyViewController class]]) {
return nil;
} else {
MyViewController *vc = [[MyViewController alloc] init];
vc.title = @"Hello";
vc.view.backgroundColor = [UIColor cyanColor];
return vc;
}
}
複製代碼
至於Pop的方法就更簡單了,直接調用下面的方法: Pop的代理方法
- (void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit {
[self showViewController:viewControllerToCommit sender:self];
}
複製代碼
有時在進入Peek但未Pop的時候,咱們能夠向上滑動選 PreviewAction Items
PreviewAction Items 是在被預覽的viewController下面添加下面方法實現的:
- (NSArray<id<UIPreviewActionItem>> *)previewActionItems {
UIPreviewAction *action1 = [UIPreviewAction actionWithTitle:@"Default" style:UIPreviewActionStyleDefault handler:^(UIPreviewAction * _Nonnull action, UIViewController * _Nonnull previewViewController) {
}];
UIPreviewAction *action2 = [UIPreviewAction actionWithTitle:@"Selected" style:UIPreviewActionStyleSelected handler:^(UIPreviewAction * _Nonnull action, UIViewController * _Nonnull previewViewController) {
}];
UIPreviewAction *action3 = [UIPreviewAction actionWithTitle:@"Destructive" style:UIPreviewActionStyleDestructive handler:^(UIPreviewAction * _Nonnull action, UIViewController * _Nonnull previewViewController) {
}];
NSArray *actions = @[action1, action2, action3];
UIPreviewActionGroup *group = [UIPreviewActionGroup actionGroupWithTitle:@"Actions Group" style:UIPreviewActionStyleDefault actions:actions];
UIPreviewAction *action4 = [UIPreviewAction actionWithTitle:@"Single Action" style:UIPreviewActionStyleDefault handler:^(UIPreviewAction * _Nonnull action, UIViewController * _Nonnull previewViewController) {
}];
NSArray *array = @[group, action4];
return array;
}
複製代碼
經過返回 UIPreviewAction
或 UIPreviewActionGroup
組成的數組實現。
前面說到若是要讓視圖控件響應Peek操做須要對其進行註冊,可是若是一個viewController中有多個控件須要響應Peek而且可能不知道什麼時候會出現的時候(譬如添加了一個tableView後,須要每個單獨的cell獨立響應一個Peek操做),是不可能一個一個註冊的,這個時候咱們能夠直接將- (void)check3DTouch
中的代碼改爲:
- (void)check3DTouch {
if (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable) {
[self registerForPreviewingWithDelegate:self sourceView:self.view];
}
}
複製代碼
咱們直接註冊整個view,根據peek代理方法中的屬性location
判斷響應的UI控件
- (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location {
if (CGRectContainsPoint(_tableView.frame, location)) {
if ([self.presentedViewController isKindOfClass:[DisplayViewController class]]) {
return nil;
} else {
location = [self.view convertPoint:location toView:_tableView];
NSIndexPath *indexPath = [_tableView indexPathForRowAtPoint:location];
NSLog(@"%@", indexPath);
DisplayViewController *displayVC = [[DisplayViewController alloc] init];
displayVC.title = [_tableView cellForRowAtIndexPath:indexPath].textLabel.text;
displayVC.view.backgroundColor = [UIColor colorWithRed:arc4random() % 256 / 256.0
green:arc4random() % 256 / 256.0
blue:arc4random() % 256 / 256.0
alpha:1.0];
// peek預覽窗口大小
displayVC.preferredContentSize = CGSizeMake(0.0, 100 * indexPath.row);
// 進入peek前不被虛化的rect
previewingContext.sourceRect = [self.view convertRect:[_tableView cellForRowAtIndexPath:indexPath].frame fromView:_tableView];
return displayVC;
}
}
if ([self.presentedViewController isKindOfClass:[MyViewController class]]) {
return nil;
} else {
if (CGRectContainsPoint(_label.frame, location)) {
MyViewController *vc = [[MyViewController alloc] init];
vc.title = @"Hello";
vc.view.backgroundColor = [UIColor cyanColor];
NSLog(@"New ViewController.");
return vc;
}
}
return nil;
}
複製代碼
這段是引用了 crazypoo/TouchNewAPI 的代碼
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
_touchPoint = [touch locationInView:_drawBoard];
}
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint currentPoint = [touch locationInView:_drawBoard];
UIGraphicsBeginImageContext(_drawBoard.frame.size);
[_drawBoard.image drawInRect:_drawBoard.frame];
CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
float lineWidth = 10.0f;
if (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable) {
lineWidth *= touch.force;
}
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), lineWidth);
CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 0.0, 0.0, 0.0, 1.0);
CGContextMoveToPoint(UIGraphicsGetCurrentContext(), _touchPoint.x, _touchPoint.y);
CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);
CGContextStrokePath(UIGraphicsGetCurrentContext());
_drawBoard.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
_touchPoint = currentPoint;
}
複製代碼
以上是個人一點淺薄的心得,本文中全部代碼都已經上傳至 kisekied/3DTouchDemo 歡迎你們交流討論。