iosswiftgestures

iOS Swift, cannot get pinch gesture to work


i have a test project that takes text from a file, adds it to a textview and displays it. i want to add some gestures but cannot seem to make it work... here is the relevant code:

class ViewController2: UIViewController, UIGestureRecognizerDelegate {

@IBOutlet var textview1: UITextView!

var pinchGesture = UIPinchGestureRecognizer()

override func viewDidLoad() {
    super.viewDidLoad()

    self.textview1.userInteractionEnabled = true
    self.textview1.multipleTouchEnabled = true

    self.pinchGesture.delegate = self
    self.pinchGesture = UIPinchGestureRecognizer(target: self, action: #selector(ViewController2.pinchRecognized(_:)))
    self.view.addGestureRecognizer(self.pinchGesture)
}


@IBAction func pinchRecognized(pinch: UIPinchGestureRecognizer) {
    self.textview1.addGestureRecognizer(pinchGesture)
    self.textview1.transform = CGAffineTransformScale(self.textview1.transform, pinch.scale, pinch.scale)
    pinch.scale = 1.0
}

any ideas? followed several tutorials but none seem to help. code is tested on actual iPhone...

thanks a lot

Edit for Solution:

@IBAction func pinchRecognized(pinch: UIPinchGestureRecognizer) {
    var pinchScale = pinchGesture.scale
    pinchScale = round(pinchScale * 1000) / 1000.0
    if (pinchScale < 1) {
        self.textview1.font = UIFont(name: self.textview1.font!.fontName, size: self.textview1.font!.pointSize - pinchScale)
        pinchScale = pinchGesture.scale
    } else {
        self.textview1.font = UIFont(name: self.textview1.font!.fontName, size: self.textview1.font!.pointSize + pinchScale)
        pinchScale = pinchGesture.scale
    }
}

thanks to nishith Singh


Solution

  • Try adding the gesture recogniser to your textview in viewDidLoad instead of adding it in pinchRecognized. Currently you are adding the pinchGesture to your view which is behind your text view and hence will not receive the touch

    var pinchGesture = UIPinchGestureRecognizer()
    

    Use this code:

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.textview1.userInteractionEnabled = true
        self.textview1.multipleTouchEnabled = true
        
        self.pinchGesture = UIPinchGestureRecognizer(target: self, action:#selector(pinchRecognized(_:)))
        self.textview1.addGestureRecognizer(self.pinchGesture)
    
        // Do any additional setup after loading the view.
    }
    
    @IBAction func pinchRecognized(_ pinch: UIPinchGestureRecognizer) {
        let fontSize = self.textview1.font!.pointSize*(pinch.scale)/2
        if fontSize > 12 && fontSize < 32{
            textview1.font = UIFont(name: self.textview1.font!.fontName, size:fontSize)
        }
    }
    

    You might have to hit and trial with the minimum and maximum font sizes as you want, right now the minimum font size is 12 and the maximum font size is 32.