0

So I have a ViewController that displays a x y graph every point is a programmatically UIButton and when is pressed it displays an alert. I want to know if it is possible to use 3DTouch peek and pop to press hard in the UIButton where it sends you to another view.

Pranav Wadhwa
  • 7,666
  • 6
  • 39
  • 61
user2822413
  • 97
  • 4
  • 9
  • Yes it is possible. Side note: I have experienced errors with '3d Touch not being available' on a 6s+. Check this out if you face the same error: http://stackoverflow.com/questions/36811061/3d-touch-not-available-on-iphone-6s/36812308#36812308 – Pranav Wadhwa Jun 30 '16 at 22:26

1 Answers1

0

Well first you need to register for previewing:

if traitCollection.forceTouchCapability == .available {
        registerForPreviewing(with: self, sourceView: view)
    }

Add the delegate to your ViewController

class ViewController: UIViewController, UIViewControllerPreviewingDelegate {

Then add the delegate methods:

func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
    let stboard = UIStoryboard(name: "HomeScreen", bundle: nil)
    guard let detailVC = stboard.instantiateViewController(withIdentifier: "DetailViewController") as? SecondVC else { return nil }
    // 1
    let pressedView = tappedView(location)
    previewingContext.sourceRect = pressedView.frame

    return detailVC
}

func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
    show(viewControllerToCommit, sender: self)
}

in (1) since you have an instance of your second view controller you can easily pass data here.

I don't know how are you managing your buttons, but I had quite a similar scenario (random UIViews moving around the screen), so as soon as a View is loaded in the MainView I append it into an array of Views.

viewArray.append(newView)

Then I created a method to check with view am I pressing

func tappedView(_ location: CGPoint) -> UIView{

    var tappedVw = UIView()

    for vw in viewArrays{
        if vw.frame.contains(location){
            tappedVw = vw as! UIView
        }
    }
    return tappedVw
}

Hope this helps