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];
}