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
}
Related
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()
}
}
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
}
}
I am playing with ProgressView. What I want to achieve is stopping at 33%, 66%, 100% checkpoints on button click. It's working okay if I use progressView.progress = 0.33, but it directly lands to the checkpoint. Instead, having it smooth and accelerating would look so nice.
I thought animateWithDuration would work but unfortunately it doesn't. After some reading, I found out that I can do something with NSTimer, but I couldn't achieve it.
var progressView: UIProgressView?
override func viewDidLoad()
{
super.viewDidLoad()
progressView = UIProgressView(progressViewStyle: UIProgressViewStyle.Default)
progressView?.center = self.view.center
progressView?.trackTintColor = UIColor.redColor()
progressView?.progressTintColor = UIColor.greenColor()
view.addSubview(progressView!)
progressView!.progress = 0.0
}
Using this answer, I achieved making it move once in every second, but how can I make it go smooth, slow in the beginning and accelerating, so looks nice.
using setProgress method and setting animation to true makes animation work.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var pb: UIProgressView!
#IBOutlet weak var btn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
pb.progress = 0.00
}
#IBAction func btnPress(sender: UIButton) {
UIView.animateWithDuration(3, animations: {
self.pb.setProgress((self.pb.progress + 0.33), animated: true)
}, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
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.
the question may seem a little confusing so I'll simplify.
I have created a view controller (JournalViewController) that holds 2 container views (MealPlanViewController, ExerciseViewController - you can ignore this container). The MealPlanViewController has a UITableView and I want to be able to delete/move the rows of the UITableview by using the left navigation Edit button item. However, when I create the navigation item in the JournalViewController, I do not know how to make it editable with the container view's UITableView.
Here is an example:
Here is my JournalViewController class:
import UIKit
class JournalViewController: UIViewController {
#IBOutlet var exerciseContainerView: UIView!
#IBOutlet var mealContainerView: UIView!
#IBOutlet var mealOrExerciseControl: UISegmentedControl!
var mealScheduleTableView: UITableView?
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.leftBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func showComponent(sender: UISegmentedControl)
{
if sender.selectedSegmentIndex == 0
{
UIView.animateWithDuration(0.5, animations:
{
self.exerciseContainerView.alpha = 0
self.mealContainerView.alpha = 1
self.navigationItem.leftBarButtonItem = self.editButtonItem()
})
}
else
{
UIView.animateWithDuration(0.5, animations:
{
self.exerciseContainerView.alpha = 1
self.mealContainerView.alpha = 0
self.navigationItem.leftBarButtonItem = nil
})
}
}
}
In the mealPlanViewController class you would set an IBAction for when the user presses the edit button. Within the IBAction you can call any functions you want that impact the Tableview.
#IBAction func editTable() {
tableView.setEditing(true, animated: true)
}
After this your TableDelegate functions take over for deleting and moving rows.