Skip to content

Instantly share code, notes, and snippets.

@AD-Paladins
Last active February 3, 2020 13:47
Show Gist options
  • Save AD-Paladins/fb9b45718a72f9b12c7abd519438d79a to your computer and use it in GitHub Desktop.
Save AD-Paladins/fb9b45718a72f9b12c7abd519438d79a to your computer and use it in GitHub Desktop.
How to use add pinch-to-zoom to a TextView (Swift)
var pinchGestureRecognizer : UIPinchGestureRecognizer!
override func viewDidLoad() {
super.viewDidLoad()
pinchGestureRecognizer = UIPinchGestureRecognizer(target: self, action: #selector(pinchGesture))
self.textView.addGestureRecognizer(pinchGestureRecognizer)
}
@objc func pinchGesture(gestureRecognizer: UIPinchGestureRecognizer ) {
print("*** Pinch: Scale: \(gestureRecognizer.scale) Velocity: \(gestureRecognizer.velocity)")
let font = self.textView.font
var pointSize = font?.pointSize
let fontName = font?.fontName
pointSize = ((gestureRecognizer.velocity > 0) ? 1 : -1) * 1 + pointSize!;
if (pointSize! < 13) { pointSize = 13}
if (pointSize! > 42) { pointSize = 42}
self.textView.font = UIFont(name: fontName!, size: pointSize!)
}
@karstengresch
Copy link

Thanks for sharing! Any idea how to preserve the formatting of an NSAttributedString rendered by the textView? I.e., you have inline headings, bold text etc. - All get away when following this approach...

@AD-Paladins
Copy link
Author

I didn't tried but you should set it's ´NSAttributedString´ inside the pinchGesture(gestureRecognizer

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment