2015-01-16 16 views
38

Sto cercando di capire come far scuotere il campo sul pulsante quando l'utente lascia il campo di testo vuoto.Animazione scuotimento per UITextField/UIView in Swift

Al momento ho il seguente codice di lavoro:

if self.subTotalAmountData.text == "" { 

    let alertController = UIAlertController(title: "Title", message: 
     "What is the Sub-Total!", preferredStyle: UIAlertControllerStyle.Alert) 
    alertController.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.Default,handler: nil)) 

    self.presentViewController(alertController, animated: true, completion: nil) 

} else { 

} 

Ma penso che sarebbe molto più attraente per avere solo la scossa campo di testo come un avviso.

Non riesco a trovare nulla per animare il campo di testo.

Qualche idea?

Grazie!

+0

Che cosa avete fatto per cercare di animare il campo di testo? –

+0

Non ho idea di dove cominciare. non ha senso per me, e non riesco a trovare alcun tutorial che mostri anche la minima variazione che posso adottare. Ho provato animateWithDuration UIViewAnimationOptions.Transition ma il codice alwasy errore su come ho senso di esso. –

+1

Esercitazioni di animazione di Google per iPhone. Ray Wanderlich di solito sono molto buoni e leggibili. –

risposta

95

È possibile modificare duration e repeatCount e modificarlo. Questo è quello che uso nel mio codice. La variazione di fromValue e toValue varierà la distanza spostata nel micromosso.

let animation = CABasicAnimation(keyPath: "position") 
animation.duration = 0.07 
animation.repeatCount = 4 
animation.autoreverses = true 
animation.fromValue = NSValue(cgPoint: CGPoint(x: viewToShake.center.x - 10, y: viewToShake.center.y)) 
animation.toValue = NSValue(cgPoint: CGPoint(x: viewToShake.center.x + 10, y: viewToShake.center.y)) 

viewToShake.layer.add(animation, forKey: "position") 
+1

Non so perché, ma ottengo questa eccezione: '2015-05-17 19: 43: 00.744 pdfdistributor [19908: 2303862] - [pdfdistributor.ViewController mLoginBT:]: selettore non riconosciuto inviato all'istanza 0x7fca90d17e00 2015-05-17 19 : 43: 00.749 pdfdistributor [19908: 2303862] *** Terminazione dell'app a causa dell'eccezione non rilevata 'NSInvalidArgumentException', motivo: '- [pdfdistributor.ViewController mLoginBT:]: selettore non riconosciuto inviato all'istanza 0x7fca90d17e00' *** Primo stack di chiamate throw: ' –

+1

Swift 3 versione: let animazione = CABasicAnimation (percorso chiave: "di posizione") animation.duration = 0,07 animation.repeatCount = 4 animation.autoreverses = true animation.fromValue = NSValue (cgPoint: cGPoint (x: txtField. center.x - 10, y: txtField.center.y)) animation.toValue = NSValue (cgPoint: CGPoint (x: txtField.center.x + 10, y: txtField.center.y)) txtField.layer. aggiungi (animazione, forKey: "posizione") – malex

85

La seguente funzione è utilizzata in qualsiasi vista.

extension UIView { 
    func shake() { 
     let animation = CAKeyframeAnimation(keyPath: "transform.translation.x") 
     animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) 
     animation.duration = 0.6 
     animation.values = [-20.0, 20.0, -20.0, 20.0, -10.0, 10.0, -5.0, 5.0, 0.0 ] 
     layer.add(animation, forKey: "shake") 
    } 
} 
+2

Aggiungi animation.repeatCount = 1000 se vuoi che continui a tremare! – Bourne

2
extension CALayer { 

    func shake(duration: NSTimeInterval = NSTimeInterval(0.5)) { 

     let animationKey = "shake" 
     removeAnimationForKey(animationKey) 

     let kAnimation = CAKeyframeAnimation(keyPath: "transform.translation.x") 
     kAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) 
     kAnimation.duration = duration 

     var needOffset = CGRectGetWidth(frame) * 0.15, 
     values = [CGFloat]() 

     let minOffset = needOffset * 0.1 

     repeat { 

      values.append(-needOffset) 
      values.append(needOffset) 
      needOffset *= 0.5 
     } while needOffset > minOffset 

     values.append(0) 
     kAnimation.values = values 
     addAnimation(kAnimation, forKey: animationKey) 
    } 
} 

Modo d'uso:

[UIView, UILabel, UITextField, UIButton & etc].layer.shake(NSTimeInterval(0.7)) 
0

Questo si basa su CABasicAnimation, ma contengono anche un effetto audio:

extension UIView{ 
    var audioPlayer = AVAudioPlayer() 
    func vibrate(){ 
     let animation = CABasicAnimation(keyPath: "position") 
     animation.duration = 0.05 
     animation.repeatCount = 5 
     animation.autoreverses = true 
     animation.fromValue = NSValue(CGPoint: CGPointMake(self.center.x - 5.0, self.center.y)) 
     animation.toValue = NSValue(CGPoint: CGPointMake(self.center.x + 5.0, self.center.y)) 
     self.layer.addAnimation(animation, forKey: "position") 
     // audio part 
     do { 
      audioPlayer = try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(mySoundFileName, ofType: "mp3")!)) 
      audioPlayer.prepareToPlay() 
      audioPlayer.play() 

     } catch { 
      print("∙ Error playing vibrate sound..") 
     } 
    } 
} 
23

Oppure si può utilizzare questo se si vuole di più parametri (in swift 3 e swift 4):

public extension UIView { 

    func shake(count : Float = 4,for duration : TimeInterval = 0.5,withTranslation translation : Float = -5) { 

     let animation : CABasicAnimation = CABasicAnimation(keyPath: "transform.translation.x") 
     animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) 
     animation.repeatCount = count 
     animation.duration = duration/TimeInterval(animation.repeatCount) 
     animation.autoreverses = true 
     animation.byValue = translation 
     layer.add(animation, forKey: "shake") 
    } 
} 

È possibile chiamare questa funzione in qualsiasi UIView, UIButton, UILabel, UITextView ecc In questo modo

yourView.shake() 

O in questo modo se si desidera aggiungere alcuni parametri personalizzati per l'animazione:

yourView.shake(count: 5, for: 1.5, withTranslation: 10) 
+1

soluzione perfetta. per un semplice shake uso 'sender.shake (count: 3, for: 0.3, withTanslation: 10)' – Danny182

7

Swift 3,0

extension UIView { 
     func shake(){ 
      let animation = CABasicAnimation(keyPath: "position") 
      animation.duration = 0.07 
      animation.repeatCount = 3 
      animation.autoreverses = true 
      animation.fromValue = NSValue(cgPoint: CGPoint(x: self.center.x - 10, y: self.center.y)) 
      animation.toValue = NSValue(cgPoint: CGPoint(x: self.center.x + 10, y: self.center.y)) 
      self.layer.add(animation, forKey: "position") 
     } 
    } 

Per utilizzare

self.vwOffer.shake() 
Problemi correlati