Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

298
Vistas
cómo iterar a través de funciones presionando un botón en Swift

Estoy aprendiendo rápido y construyendo una ARApp, pero parece que no puedo entender cómo iterar a través de algunas funciones con cada pulsación de botón por separado. He creado 3 funciones con animación incorporada y quiero presionar el botón una vez y activar la función Animación # 1, luego toque el botón nuevamente para continuar con la función Animación # 2 y así sucesivamente.

 @IBAction func nextAnimation(_ sender: UIButton) { funcAnimation#1() funcAnimation#2() funcAnimation#3() }

por supuesto, el problema aquí es que todos se activan a la vez. Me gustaría iterar solo al presionar el botón para cada pulsación individual. Además, también me gustaría tener un botón de retroceso que revierta la animación actual a la animación anterior. Leí en la documentación de Apple que hay un método addTarget pero no entiendo cómo funciona o cómo implementarlo. ¡Por favor ayuda!

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

Tu código debería ser así:

 // You can define this variable globally... var counter = 0 @IBAction func nextAnimation(_ sender: UIButton) { if (counter == 0) { funcAnimation1() // Increase counter count by 1 and you can add this line to completion of animation. // You can also disable your button interaction until your animation gets complete and that way you can handle your UI count += 1 } else if (counter == 1) { funcAnimation2() // Increase counter count by 1 and you can add this line to completion of animation. count += 1 } else if (counter == 2) { funcAnimation3() // set your counter to 0 again to loop through your animation. counter = 0 } }

Su acción de retroceso debería verse así:

 @IBAction func backAnimation(_ sender: UIButton) { if (counter == 0) { funcAnimation1() // set your counter to 2 again to loop through your animation. count = 2 } else if (counter == 1) { funcAnimation2() // decrease counter count by 1 and you can add this line to completion of animation. // You can also disable your button interaction until your animation gets complete and that way you can handle your UI count -= 1 } else if (counter == 2) { funcAnimation3() // decrease counter count by 1 and you can add this line to completion of animation. count -= 1 } }
over 4 years ago · Santiago Trujillo Denunciar

0

¡De otra manera!

Simplemente configure la etiqueta del botón 1 (Ej. btnObj.tag=1 )

Y administre los métodos en acción del botón como

Mi sugerencia también es administrar el flag para la animación, por ejemplo, si la primera animación está en proceso, la segunda estará esperando el final y después de terminar la primera animación, se hará clic en el botón para que su animación no coincida.

 var isAnimated = false; @IBAction func myAnimationMethod(_ sender: UIButton) { if isAnimated {return} // Or display appropriate message by alert if (sender.tag == 1) { isAnimated=true funcAnimation1(...Your Code... After finish to set isAnimated=false) sender.tag = 2 } else if (sender.tag == 2) { isAnimated=true funcAnimation2(...Your Code... After finish to set isAnimated=false) sender.tag = 3 } else if (sender.tag == 3) { isAnimated=true funcAnimation3(...Your Code... After finish to set isAnimated=false) sender.tag = 1 } }
over 4 years ago · Santiago Trujillo Denunciar

0

Puede reenviar sus animaciones y volver al estado de animación anterior a través de un botón de retroceso como este.

Paso 1: declarar dos variables de tipo entero

 var tapCount = 0 //For forwarding your animations from first to third var currentAnimation = 0 // For reversing the animation from current animation

Paso 2: en su función IBAction

 @IBAction func nextAnimation(_ sender: Any) { if tapCount == 0 { if currentAnimation == 1 { Animation2() } else { Animation1() } tapCount += 1 } else if tapCount == 1 { if currentAnimation == 2 { Animation3() } else { Animation2() } tapCount += 1 } else if tapCount == 2 { if currentAnimation == 3 { Animation1() } else { Animation3() } tapCount = 0 } }

Paso 3: En tus funciones

 func Animation1() { currentAnimation = 1 print("First Animation") } func Animation2() { currentAnimation = 2 print("Second Animation") } func Animation3() { currentAnimation = 3 print("third Animation") }

Paso 4: Por último, para invertir la animación desde el estado actual

 @IBAction func backAnimation(_ sender: Any) { if currentAnimation == 2 { Animation1() } else if currentAnimation == 3 { Animation2() } else { } tapCount = 0 }

Espero eso ayude !!

Para el método addTarget(_:action:for:) , esto se puede hacer sin conectar una IBAction y declararla en viewWillAppear o viewDidLoad según sea necesario. Asociará un objeto de destino y un método de acción con el control.

Por ejemplo :

 override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. nextButton.addTarget(self, action: #selector(self. nextAnimation), for: .touchUpInside) //Declared outlet as nextButton backButton.addTarget(self, action: #selector(self. backAnimation), for: .touchUpInside) //Declared outlet as backButton and this adds a target } @objc func nextAnimation(sender: UIButton) { // Do your stuff for next animation } @objc func backAnimation(sender: UIButton) { // Do your stuff for previous animation }
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda