Search code examples
iosswiftmkmapviewuianimationuiblureffect

UITextFieldShouldChange being called twice


I want a MKMapView to blur if there is no entry in a text field by using UIVisualEffectsView over top of the map, i also want it to aniamte, Right now the shouldChangeCharactersInRange its getting called twice when someone starts typing and not at all when the user removes all text from the UITextField. Heres my code

import UIKit
import MapKit
import Parse

class HomeAddressViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate, UITextFieldDelegate {

let locationManager = CLLocationManager()

@IBOutlet var activityIndicator: UIActivityIndicatorView!
@IBOutlet var homeAddressField: UITextField!
@IBOutlet var homeAddressMap: MKMapView!
@IBOutlet var blurryMap: UIVisualEffectView! = UIVisualEffectView()
override func viewDidLoad() {
    super.viewDidLoad()

    activityIndicator.hidden = true

    homeAddressField.delegate = self

    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestWhenInUseAuthorization()
    locationManager.startUpdatingLocation()

    blurAndUnblurMap()


}
func blurAndUnblurMap() {
    if homeAddressField.text?.characters.count == 0 {
        UIView.animateWithDuration(1, animations: {
            self.blurryMap.effect = UIBlurEffect(style: .Light)
        })
    } else {
        UIView.animateWithDuration(0.5, animations: {
            self.blurryMap.effect = nil
        })
    }
}

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    blurAndUnblurMap()
    return true
}
}

Solution

  • Why don't you do this instead?

    homeAddressField.addTarget(self, "someFunction:", forControlEvents: .EditingChanged)
    

    Get text changes and act accordingly.