3D 触摸与 Swift
iPhone 6s Plus 已经引入了 3D touch。这个新的界面层添加了两个行为:Peek 和 Pop。
简而言之,偷看和流行
偷看 - 努力
流行 - 真的很难
检查 3D 支持
你应该检查设备是否具有 3D 触摸支持。你可以通过检查 UITraitCollection 对象的 forceTouchCapability 属性的值来执行此操作。UITraitCollection 描述了应用程序的 iOS 界面环境。 **
if (traitCollection.forceTouchCapability == .Available) {
registerForPreviewingWithDelegate(self, sourceView: view)
}
实现委托
你需要在类中实现 UIViewControllerPreviewingDelegate 的两个方法。其中一种方法是偷看,另一种是流行为。
为窥视实现的方法是 previewingContext 。
func previewingContext(previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
guard let indexPath = self.tableView.indexPathForRowAtPoint(location), cell = self.tableView.cellForRowAtIndexPath(indexPath) as? <YourTableViewCell> else {
return nil
}
guard let datailVC = storyboard?.instantiateViewControllerWithIdentifier("<YourViewControllerIdentifier>") as? <YourViewController> else {
return nil
}
datailVC.peekActive = true
previewingContext.sourceRect = cell.frame
// Do the stuff
return datailVC
}
为 pop 实现的方法是 previewingContext 。 :)
func previewingContext(previewingContext: UIViewControllerPreviewing, commitViewController viewControllerToCommit: UIViewController) {
let balanceViewController = viewControllerToCommit as! <YourViewController>
// Do the stuff
navigationController?.pushViewController(balanceViewController, animated: true)
}
如你所见,它们是重载方法。你可以以任何方式使用 3D touch 来实现这些方法。
Objective-C
//Checking for 3-D Touch availability
if ([self.traitCollection respondsToSelector:@selector(forceTouchCapability)] &&
(self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable))
{
[self registerForPreviewingWithDelegate:self sourceView:self.view];
}
//Peek
- (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext
viewControllerForLocation:(CGPoint)location {
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
Country *country = [self countryForIndexPath:indexPath];
if (country) {
CountryCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
if (cell) {
previewingContext.sourceRect = cell.frame;
UINavigationController *navController = [self.storyboard instantiateViewControllerWithIdentifier:@"UYLCountryNavController"];
[self configureNavigationController:navController withCountry:country];
return navController;
}
}
return nil;
}
//Pop
- (void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit {
[self showDetailViewController:viewControllerToCommit sender:self];
}