Use animations to show color sequence (Swift) - ios

Hi I'm new to Swift and I want to create a color memory game for IPhone where your app gives you a sequence of colors and you have to repeat it by pressing the right buttons. The sequence becomes longer and longer everytime you pressed the right buttons of the previous sequence.
I want the app to show which button is pressed by using an animation on the button. The sequence will make the buttons flash and then the user can recreate the sequence.
I have a method that does the flash(), which is a part of a class which is an extension of UIButton
func flash() {
let flash = CABasicAnimation(keyPath: "opacity")
flash.duration = 0.2
flash.fromValue = 1
flash.toValue = 0.1
flash.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
flash.autoreverses = true
flash.repeatCount = 1
layer.add(flash, forKey: nil)
}
When I perform this method on a sequence of buttons it flashes all of the buttons, written in the sequence, at the same time. This is not the way I want it of course, I want the buttons to flash one after another.
// ViewController.swift
import UIKit
import SpriteKit
class GameViewController: UIViewController {
var colorPattern = [Int]()
#IBOutlet weak var buttonGreen: UIButton!
#IBOutlet weak var buttonRed: UIButton!
#IBOutlet weak var buttonBlue: UIButton!
#IBOutlet weak var buttonYellow: UIButton!
var buttons = [UIButton]()
override func viewDidLoad() {
super.viewDidLoad()
buttons = [buttonGreen, buttonRed, buttonBlue, buttonYellow]
colorPattern = [0, 1, 2, 0, 1, 2]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func colorButtonTouched(_ sender: UIButton) {
print("button touched: ", sender.titleLabel!.text!)
//sender.flash()
doPattern()
}
func doPattern() {
UIView.animateKeyframes(withDuration: 1, delay: 0, options: [.calculationModeCubic], animations: {
// Add animations
for index in self.colorPattern{
print(index);
UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 1, animations: self.buttons[index].flash)
}
}, completion:{ _ in
print("I'm done!")
})
}
}
When I perform this code button 1, 2 and 3 flash at the same time. Is there a way to fix this? or are animations just not the right way to go with looping sequences.

Try this
var currentButtonIndex = 0
func doPattern()
{
let currentButton = self.buttons[self.currentButtonIndex]
UIView.animateKeyframes(withDuration: 1, delay: 0, options: [.autoreverse], animations: {
currentButton.alpha = 0
}) { (complete) in
currentButton.alpha = 1
if self.currentButtonIndex == self.buttons.count - 1
{
self.currentButtonIndex = 0
return
}
self.currentButtonIndex += 1
self.doPattern()
}
}

Related

How can I check the alpha of container views with the button in the bottom view of the container view-Swift 4 -IOS

Main.StoryBoard in this way
class ForgotPasswordContainerControl: UIViewController {
#IBOutlet var screenStep1: UIView?
#IBOutlet var screenStep2: UIView?
#IBOutlet var screenStep3: UIView?
override func viewDidLoad() {
super.viewDidLoad()
self.screenStep1?.alpha = 1.0
self.screenStep2?.alpha = 0.0
self.screenStep3?.alpha = 0.0
}
#IBAction func step1ButtonClick(_ sender: UIButton) {
UIView.animate(withDuration: 0.5, animations: {
self.screenStep1?.alpha = 0.0
self.screenStep2?.alpha = 1.0
self.screenStep3?.alpha = 0.0
print("clicked button1 ")
})
print("clicked button2 ")
}
}
My code is working in viewdDidLoad, clicking the button prints is working
but Alpha does not work, how can i do?

Fade In & Out Animation With The Same UIImageView

I want to know whether I can create any type of animation with the same UIImageView. Whenever the user clicks a button, it will change the photo using a fade in animation.
import UIKit
class ViewController: UIViewController {
var maximum: Int = 2
var number: Int = 0
var imageNames = ["0", "1"]
#IBOutlet weak var mainImage: UIImageView!
#IBOutlet weak var nextButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Gradient
nextButton.setGradientBackground(colorOne: UIColor(red:0.00, green:0.78, blue:1.00, alpha:1.0), colorTwo: UIColor(red:0.00, green:0.45, blue:1.00, alpha:1.0))
// Drop Shadows
nextButton.layer.shadowColor = UIColor.black.cgColor
nextButton.layer.shadowOffset = CGSize(width: 1, height: 1)
nextButton.layer.shadowRadius = 25
nextButton.layer.shadowOpacity = 0.10
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func changeImages(_ sender: Any) {
number = Int(arc4random_uniform(UInt32(maximum)))
mainImage.image = UIImage(named: "\(number).jpg")
}
}
There is no attempt of me trying to create an animation.
I was just hoping someone could help me create one.
you need to animate alpha value. make a fade in and fade out function like this :
func fadeIn(){
UIView.animate(withDuration: 3) {
self.my.alpha = 0.0
}
}
func fadeOut(){
UIView.animate(withDuration: 3.0) {
self.my.alpha = 1.0
}
}
Then use it when you change your image:
fadeIn()
changeImages() /* your change image logic without animation */
fadeOut()
You can try to animate the alpha
#IBAction func changeImages(_ sender: Any) {
number = Int(arc4random_uniform(UInt32(maximum)))
mainImage.image = UIImage(named: "\(number).jpg")
mainImage.alpha = 0
UIView.animate(withDuration: 1.5, animations: {
self.mainImage.alpha = 1
}
}

Swift viewDidLoad() in second View Controller Scene not working

I'm a beginner at swift and Xcode, so this question may sound very simple.
I have two view controllers, connected by a segue. My first view controller scene runs code from the viewDidLoad() function, and then calls the .performSegue() function for the second view controller scene to get displayed.
But now, I want to run code in that new .swift file. viewDidLoad() doesn't seem to work, so how do I get around this problem? Where else could I put my code, or what function should it be in?
EDIT
// Show main menu
self.performSegue(withIdentifier: "MenuSegue", sender: self)
is how I am switching between view controllers. The buttons display, but anything I write in viewDidLoad() does not work
EDIT 2
My code for ViewController.swift:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var startScreen: UIStackView! // H2O start screen
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// Display start screen for 2 seconds before fading out
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2, execute: {
// Fade out start screen
UIView.animate(withDuration: 1, animations: {self.startScreen.alpha = 0})
// Wait 1 second from when start screen starts to fade out
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: {
// Show main menu
self.performSegue(withIdentifier: "MenuSegue", sender: self)
})
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
And for MenuViewController.swift:
import UIKit
class MenuViewController: UIViewController {
#IBOutlet weak var playButton: UIButton! // Play button
#IBOutlet weak var settingsButton: UIButton! // Settings button
#IBOutlet weak var volumeButton: UIButton! // Volume button
#IBOutlet weak var volumeStack: UIStackView! // Volume stack
#IBOutlet weak var volumePercentage: UILabel! // Volume percentage
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
print("Hello")
// Slowly display everything
playButton.alpha = 0
settingsButton.alpha = 0
volumeButton.alpha = 0
volumeStack.alpha = 0
// Fade out start screen
UIView.animate(withDuration: 1, animations: {self.playButton.alpha = 1; self.settingsButton.alpha = 1; self.volumeButton.alpha = 1; self.volumeStack.alpha = 1})
print("Hi")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func settings(_ sender: UIButton) {
// If the settings are hidden
if volumeButton.alpha == 0 {
// Rotate settings button to open settings
UIView.animate(withDuration: 0.5, animations: {sender.transform = CGAffineTransform(rotationAngle: .pi * -0.999)})
// Show extended settings
UIView.animate(withDuration: 0.5, animations: {self.volumeButton.alpha = 1})
}
else {
// Rotate settings button back to normal
UIView.animate(withDuration: 0.5, animations: {sender.transform = CGAffineTransform(rotationAngle: 0.0)})
// Hide extended settings
UIView.animate(withDuration: 0.5, animations: {self.volumeButton.alpha = 0})
}
}
#IBAction func volumeSlider(_ sender: UISlider) {
// Get slider value rounded to nearest 5
let value = round(sender.value / 5) * 5
// Set the value to nearest 5
sender.value = value
// Show volume percentage
volumePercentage.text = "\(Int(value))%"
}
#IBAction func playButton(_ sender: UIButton) {
// Hide all settings
settingsButton.alpha = 0
volumeButton.alpha = 0
volumeStack.alpha = 0
// Hide play button
sender.alpha = 0
}
}
Add your animation code inside viewWillAppear() method.
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
//Add animation code here
}

SWRevealViewController UIButton does not work after using another UIButton

It may sound confusing, but just bear with me.
I have 2 buttons in my ViewController.swift. One that reveals a side menu (this uses the SWRevealViewController), and another one revealing another ViewController.
Once I run the app, it lets me use the slide menu button no problem. However, if I use the other button to reveal another ViewController, THEN come back to the original ViewController (the one with the slide-out menu button), the slide-out-menu button does not work, rather it just blinks and does no action.
I tried programming it and looking at examples, however I have no luck.
Here is my viewController.swift:
import UIKit
class ViewController: UIViewController {
#IBOutlet var BTN4: UIButton!
#IBOutlet var BTN3: UIButton!//This is the button that brings you to the other viewController
#IBOutlet var BTN2: UIButton!
#IBOutlet var BTN1: UIButton!
#IBOutlet var Button: UIButton! //This is the SWRevealViewController being called
#IBOutlet var Bar: UINavigationItem!
var varView = Int()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = UIColor(red: 50 / 255.0, green: 132 / 255.0, blue: 255 / 255.0, alpha: 1.0)
BTN1.alpha = 1.0
BTN4.alpha = 0
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func Clicked(sender: AnyObject) {
UIView.animateWithDuration(1.0, animations: ({
self.BTN2.transform = CGAffineTransformMakeTranslation(0, -90)
self.BTN3.transform = CGAffineTransformMakeTranslation(0, -180)
self.BTN4.transform = CGAffineTransformMakeTranslation(0, 0)
self.BTN1.alpha = 0
self.BTN4.alpha = 1.0
}))
}
#IBAction func ClickedAgain(sender: AnyObject) {
UIView.animateWithDuration(1.0, animations: ({
self.BTN2.transform = CGAffineTransformMakeTranslation(0, 0)
self.BTN3.transform = CGAffineTransformMakeTranslation(0, 0)
self.BTN4.transform = CGAffineTransformMakeTranslation(0, 0)
self.BTN1.alpha = 1.0
self.BTN4.alpha = 0
}))
}
#IBAction func ButtonClicked(sender: AnyObject) {
Button.addTarget(self.revealViewController(), action:#selector(SWRevealViewController.revealToggle(_:)), forControlEvents:UIControlEvents.TouchUpInside)//This is the SWRevealViewController Action
}
}
Any help on this? I know it is a lot, but any type of help would be fantastic.

Swift animation not sticking [duplicate]

This question already has an answer here:
UIView layout being reset
(1 answer)
Closed 8 years ago.
I have a button when clicked I move an imageView with animation to another location on the screen with the following code:
#IBOutlet var CurrentPlayerTotal: UILabel!
#IBOutlet var Player1: UIImageView!
UIImageView.animateWithDuration(1.0, animations: {
self.Player1.frame = CGRect(x: 16, y: 178, width: 250, height: 350)
})
The image moves fine.
I have another button that updates a label on the screen.
#IBAction func Sub1(sender: AnyObject) {
currentTotal -= 1
CurrentPlayerTotal.text = "\(currentTotal )"
}
When I click this button the image returns to the original location. Why is this happening?
Here is a more complete code snippet
var currentTotal : Int = 0
var currentPlayer : Int = 1
var numberOfPlayers : Int = 6
#IBOutlet var CurrentPlayerTotal: UILabel!
#IBOutlet var CurrentPlayerNme: UILabel!
#IBOutlet var Player1: UIImageView!
override func viewDidAppear(animated: Bool) {
UIImageView.animateWithDuration(1, delay: 1.0, options: .CurveEaseOut, animations: {
var player = self.Player1.frame
player = CGRect(x: 16, y: 178, width: 250, height: 350)
self.Player1.frame = player
}, completion: { finished in
println("done")
})
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
// SUBTRACT
#IBAction func Sub1(sender: AnyObject) {
currentTotal -= 1
CurrentPlayerTotal.text = "\(currentTotal )"
}
The app begins the image moves to the correct spot. When I click on the button bound to the Sub1 func the image pops back to the original spot.
Try first option if it works then okay, otherwise try the second one, it will work definitely.
self.player1.layoutIfNeeded()
self.player1 setNeedsDisplay()
Make outlet of the NSLayoutConstraint for uiimageview and plus/minus it as per your need rather chaging frame of the uimageview.

Resources