pkcanvasview inside scrollview in swift

To add a PKCanvasView inside a UIScrollView, you can do the following:

  1. First add a UIScrollView in your view controller's view either from storyboard or programmatically. Set its constraints as required.

  2. Create a PKCanvasView object and add it as a subview of this UIScrollView. Don't forget to set its constraints as required.

  3. Set the content size of the UIScrollView to be equal to the frame size of the PKCanvasView.

  4. Finally, set the delegate of the PKCanvasView to be the view controller where you are adding this UIScrollView. This is required to receive drawing notifications.

main.swift
import UIKit
import PencilKit

class MyViewController: UIViewController, PKCanvasViewDelegate {
    
    // Outlet to the scroll view from storyboard
    @IBOutlet weak var scrollView: UIScrollView!
    
    // Create a PKCanvasView object
    let canvasView = PKCanvasView(frame: CGRect(x: 0, y: 0, width: 500, height: 500))
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Add the canvas view as a subview of the scroll view
        scrollView.addSubview(canvasView)
        
        // Set the constraints of the canvas view to be equal to its superview
        canvasView.translatesAutoresizingMaskIntoConstraints = false
        canvasView.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true
        canvasView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor).isActive = true
        canvasView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor).isActive = true
        canvasView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor).isActive = true
        
        // Set the content size of the scroll view to be equal to the frame size of the canvas view
        scrollView.contentSize = canvasView.frame.size
        
        // Set the delegate of the canvas view to be this view controller
        canvasView.delegate = self
    }
    
    // Implement PKCanvasViewDelegate methods as required
    // ...
}
1400 chars
35 lines

Note: If you want the user to be able to scroll the UIScrollView while drawing on the PKCanvasView, you need to set the delaysContentTouches property of the UIScrollView to false.

gistlibby LogSnag