Fade In & Out Animation With The Same UIImageView - ios

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
}
}

Related

Use animations to show color sequence (Swift)

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()
}
}

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
}

VisualEffectView in Swift and Xcode9

Picture of my code
import UIKit
class ViewController: UIViewController {
#IBOutlet var addItemView: UIView!
#IBOutlet weak var visualEffectView: UIVisualEffectView!
var effect: UIVisualEffect!
override func viewDidLoad() {
super.viewDidLoad()
effect = visualEffectView.effect
visualEffectView.effect = nil
addItemView.layer.cornerRadius = 5
}
func animateIn(){
self.view.addSubview(addItemView)
addItemView.center = self.view.center
addItemView.transform = CGAffineTransform.init(scaleX: 1.3, y: 1.3)
addItemView.alpha = 0
UIView.animate(withDuration: 0.4){
self.visualEffectView.effect = self.effect
self.addItemView.alpha = 1
self.addItemView.transform = CGAffineTransform.identity
}
}
#IBAction func sourcesButton(_ sender: Any) {
animateIn()
}
#IBAction func sourceDone(_ sender: Any) {
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
I am trying to make a blurry modal that pops up when the user clicks a button, but for some reason this code is not executing. I was following a tutorial on youtube (Youtube Link) I would appreciate the help.
Create blur view like this instead:
var blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Dark)
var blurEffectView = UIVisualEffectView(effect: blurEffect)
view.addSubview(blurEffectView)
And after it is created you can set alpha to 0 and animate it to 1.
Please note that animation with UIBlurEffect looks horrible on the device :p

Swift Run An NSTimer Automatically

I'm making an app and using NSTimer to make the timer in my app.But I need the NSTimer to run when the scene start.I have two scene in my app a homescreen and the app it's self here is my code viewcontroller.swift (The second scene the first scene in empty) And btw it's my 3 day using swift and i'm in middle school ;).
import UIKit
var Number = 2
var Answer = Number * 2
var score = 0
var scorelabel = "Score: "
var Timer = NSTimer()
var Counter = 10
class SecondViewController: UIViewController {
#IBOutlet weak var RightAndWrongLabel: UILabel!
#IBOutlet weak var TimerLabel: UILabel!
#IBOutlet weak var RightAndWrong: UIImageView!
#IBOutlet weak var ScoreIabel: UILabel!
#IBOutlet weak var UserInputAnswer: UITextField!
#IBOutlet weak var Question: UILabel!
#IBOutlet weak var TimerOut: UIImageView!
var seconds = 0
var timeison = true
#IBAction func ConfirmAnswer(sender: AnyObject) {
let UserAnswer = Int(UserInputAnswer.text!)
if UserAnswer == Answer {
print("Your right")
Number += 2
score += 1
ScoreIabel.text = "Score: \(score)"
Question.text = "\(Number) x 2"
UserInputAnswer.text = ""
Answer = Number * 2
RightAndWrong.image = UIImage(named: "Label")
RightAndWrongLabel.hidden = false
RightAndWrongLabel.text = "Right!"
RightAndWrongLabel.textColor = UIColor(red: 0, green: 225, blue: 0, alpha: 1)
} else {
UserInputAnswer.text = ""
RightAndWrong.image = UIImage(named: "Label")
RightAndWrongLabel.hidden = false
RightAndWrongLabel.text = "Wrong!"
RightAndWrongLabel.textColor = UIColor(red: 225, green: 0, blue: 0, alpha: 1)
}
}
func DisplayTimer() {
Timer = NSTimer.scheduledTimerWithTimeInterval(1, target:self, selector: Selector("updateCounter"), userInfo: nil, repeats: true)
}
func updateTimer(){
TimerLabel.text = String(Counter--)
}
override func viewDidLoad() {
super.viewDidLoad()
UserInputAnswer.keyboardType = UIKeyboardType.NumberPad
RightAndWrongLabel.hidden = true
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
3
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
Swift 2.x :
func DisplayTimer() {
Timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target:self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
}
func updateTimer() {
if Counter != 0 { TimerLabel.text = "\(Counter -= 1)"
} else {
Timer.invalidate()
// call a game over method here...
}
}
override func viewDidLoad() {
super.viewDidLoad()
...
// start the timer when this controller shows up
DisplayTimer()
TimerLabel.text = "\(Counter)"
...
}
If you want to start your timer when the scene loads call DisplayTimer() under
override func viewDidLoad() when the view is loaded
Also if you want to update your label every second, the selector in your NSTimer is calling updateCounter not updateTimer

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.

Resources