How to Draw Digital Signatures in iOS Using Swift 5: A Developer’s Tutorial

Inwizards-blog-img

Digital signatures are essential for mobile apps that handle contracts, forms, or approvals. Whether you’re building a banking app, a document management system, or a delivery app, enabling users to sign directly on their device enhances usability and compliance. In this tutorial, we’ll show you how to implement digital signature capture in iOS using Swift 5, step by step.

Table of Contents

  1. Why Digital Signatures Matter
  2. Project Setup in Xcode
  3. Creating a Signature View
  4. Integrating the Signature View in Your ViewController
  5. Saving Signatures to Photos or PDF
  6. Testing and Debugging
  7. FAQs

Why Digital Signatures Matter

Digital signatures improve workflows by:

  • Eliminating the need for printing, signing, and scanning.
  • Reducing errors in document handling.
  • Increasing trust and compliance in mobile forms.

In iOS, capturing a signature is straightforward using UIView for drawing, combined with UIImage for saving the results.

Project Setup in Xcode

  1. Open Xcode and create a new project.
    • Template: App
    • Language: Swift
    • Interface: Storyboard
  2. Name your project, e.g., DigitalSignatureDemo.
  3. Ensure you select iOS 14+ or later for modern Swift compatibility.

Creating a Signature View

We’ll create a custom UIView that tracks touches to draw a signature.

Step 1: Create a Swift file

  1. Go to File → New → File → Swift File
  2. Name it SignatureView.swift.

Step 2: Implement the drawing logic

import UIKit

 

class SignatureView: UIView {

 

private var lines: [Line] = []

private var strokeColor: UIColor = .black

private var lineWidth: CGFloat = 2.0

 

required init?(coder: NSCoder) {

super.init(coder: coder)

self.backgroundColor = .white

}

 

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

guard let touch = touches.first else { return }

let newLine = Line(points: [touch.location(in: self)], color: strokeColor, width: lineWidth)

lines.append(newLine)

setNeedsDisplay()

}

 

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {

guard let touch = touches.first, var lastLine = lines.popLast() else { return }

lastLine.points.append(touch.location(in: self))

lines.append(lastLine)

setNeedsDisplay()

}

 

override func draw(_ rect: CGRect) {

super.draw(rect)

guard let context = UIGraphicsGetCurrentContext() else { return }

context.setLineCap(.round)

 

for line in lines {

context.setStrokeColor(line.color.cgColor)

context.setLineWidth(line.width)

for (i, point) in line.points.enumerated() {

if i == 0 { context.move(to: point) }

else { context.addLine(to: point) }

}

context.strokePath()

}

}

 

func clear() {

lines.removeAll()

setNeedsDisplay()

}

 

func getSignatureImage() -> UIImage {

UIGraphicsBeginImageContextWithOptions(bounds.size, false, 0)

drawHierarchy(in: bounds, afterScreenUpdates: true)

let signature = UIGraphicsGetImageFromCurrentImageContext()!

UIGraphicsEndImageContext()

return signature

}

}

 

// Helper struct

struct Line {

var points: [CGPoint]

var color: UIColor

var width: CGFloat

}

 

Integrating the Signature View in Your ViewController

  1. Open Main.storyboard and add a UIView.
  2. Set its class to SignatureView in the Identity Inspector.
  3. Add two UIButtons:
    • Clear to reset the signature.
    • Save to save the signature image.
  4. Connect your IBOutlet and IBAction in ViewController.swift.

import UIKit

 

class ViewController: UIViewController {

 

@IBOutlet weak var signatureView: SignatureView!

@IBOutlet weak var imageView: UIImageView!

 

@IBAction func clearSignature(_ sender: UIButton) {

signatureView.clear()

imageView.image = nil

}

 

@IBAction func saveSignature(_ sender: UIButton) {

let signature = signatureView.getSignatureImage()

imageView.image = signature

UIImageWriteToSavedPhotosAlbum(signature, nil, nil, nil)

}

}

 

Saving Signatures to PDF (Optional)

You can also save the signature as a PDF for contracts or forms:

func saveSignatureAsPDF(signature: UIImage) {

let pdfData = NSMutableData()

UIGraphicsBeginPDFContextToData(pdfData, CGRect(origin: .zero, size: signature.size), nil)

UIGraphicsBeginPDFPage()

signature.draw(in: CGRect(origin: .zero, size: signature.size))

UIGraphicsEndPDFContext()

 

let documentsPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

let pdfPath = documentsPath.appendingPathComponent(“signature.pdf”)

pdfData.write(to: pdfPath, atomically: true)

print(“Saved PDF to: \(pdfPath)”)

}

 

Testing and Debugging

  • Run the app on simulator or a real device.
  • Draw your signature and verify it appears in UIImageView.
  • Test clear and save functionality.
  • For PDFs, check the Documents folder in the simulator or use Files app on a real device.

Developer Tips

  • Adjust strokeColor and lineWidth for signature style.
  • Consider adding undo functionality by keeping a history stack of lines.
  • For production apps, secure signature storage and encryption may be required.
  • Optimize performance for large signature images by limiting the number of stored points.

FAQs

Q1: Can I capture signatures in SwiftUI?
Yes! You can wrap SignatureView in UIViewRepresentable to use it in SwiftUI apps.

Q2: How do I add multiple pages for signatures in PDF?
Use UIGraphicsBeginPDFPage() for each page and draw signatures separately.

Q3: How to export signatures to cloud storage?
Convert the signature image to Data using pngData() or jpegData() and upload to Firebase, AWS S3, or your preferred backend.

Q4: Can I customize the pen color and thickness?
Yes! Modify strokeColor and lineWidth in SignatureView. You can add a UI picker for dynamic selection.

Q5: How to optimize for large screen devices like iPad?
Scale the drawing points relative to the bounds.size to maintain proportionality on all devices.

Conclusion

Capturing digital signatures in iOS is simple and highly practical for modern apps. By using a custom UIView and Swift 5, you can build a robust, reusable, and customizable signature feature. This tutorial equips you with the core functionality, plus optional PDF export for real-world applications.

CTA: Ready to add digital signature functionality to your app? Try this Swift 5 implementation and integrate it with your forms or contracts today!

How to Draw Digital Signatures in iOS Using Swift 5: A Developer’s Tutorial

Post navigation


0 0 vote
Article Rating
Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Sadam Hussain Churahi
Sadam Hussain Churahi
7 years ago

i need code in swift of digital signature application

1
0
Would love your thoughts, please comment.x
()
x