I'm trying change an uiimage control's containing image by clicking a button in swift. For this, i wrote a simple a "guess how many fingers i'm holding up" app. I've read some stackoverflow articles but couldn't solve the problem. Below you can see my code and my ui. How can i change change image on click?
Here's my code:
import UIKit
class ViewController: UIViewController {
#IBOutlet var myImageView: UIImageView!
#IBOutlet var inputField: UITextField!
#IBAction func clickedGuessButtonAction(sender: AnyObject) {
println("Guess button clicked")
var randomX = Int(arc4random()%6)
println("randomX = \(randomX)")
var guess = inputField.text.toInt();
let image0 = UIImage(named: "images/qm.jpg")
let image1 = UIImage(named: "images/tick.jpg")
let image2 = UIImage(named: "images/cross.jpg")
if((inputField.text) != nil){
if(guess == randomX){
println("correct")
myImageView.image=UIImage(named: "tick.jpg") // THIS IS NOT WORKING
myImageView.image=image1 // THIS IS NOT WORKING TOO
inputField.resignFirstResponder();// hides keyboard
}
else
{
println("wrong")
myImageView.image=UIImage(named: "cross.jpg")
inputField.resignFirstResponder();//hides keyboard
}
}
else{
println("invalid input. requires integer only")
inputField.resignFirstResponder();// hides keyboard
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
And here's my UI:
You don't need to specify either the asset catalog's name or the image file's extension. Try removing those. For example,
myImageView.image = UIImage(named: "tick")
It may depend on the version of Xcode you are using. For me the following worked:
ImageView.image = UIImage(named: "Elephants.jpg")
In Swift:
myImageView = "nameOfImage";
Related
I can change background image on viewDidLoad func like this:
let myBackgroundImage = UIImageView (frame: UIScreen.main.bounds)
myBackgroundImage.image = UIImage(named: "wallpaper-1-iphone-8-plus.png")
myBackgroundImage.contentMode = UIViewContentMode.scaleAspectFill
self.view.insertSubview(myBackgroundImage, at: 0)
i would like to do same action with button click like this:
#IBAction func flip4btn5(_ sender: Any)
{
let myBackgroundImage = UIImageView (frame: UIScreen.main.bounds)
myBackgroundImage.image = UIImage(named: "wallpaper-2-iphone-8-plus.png")
myBackgroundImage.contentMode = UIViewContentMode.scaleAspectFill
self.view.insertSubview(myBackgroundImage, at: 0)
}
but it does not change background image. Why ? What do you think ?
I'm using Swift 4.1.
Don't create a new image. just change the picture of the first UIImage in your button action like this:
myBackgroundImage.image = UIImage(named: "wallpaper-2-iphone-8-plus.png")
Try this code, It's working fine.
class ViewController: UIViewController {
var myBackgroundImage = UIImageView (frame: UIScreen.main.bounds);
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
myBackgroundImage.image = UIImage(named: "wallpaper-1-iphone-8-plus.png")
myBackgroundImage.contentMode = UIViewContentMode.scaleAspectFill
self.view.insertSubview(myBackgroundImage, at: 0)
}
#IBAction func flip4btn5(_ sender: UIButton) {
myBackgroundImage.image = UIImage(named: "wallpaper-2-iphone-8-plus.png")
}
}
Don't keep adding UIImageViews everytime you want to change the background image.
Place a UIImageView in the view hierarchy where it is needed and keep a reference to it. Then set the image property on it as needed.
class ViewController: UIViewController {
#IBOutlet weak var backgroundImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
backgroundImageView.image = UIImage(named: "wallpaper-1-iphone-8-plus.png")
}
#IBAction func flip4btn5(_ sender: Any) {
backgroundImageView.image = UIImage(named: "wallpaper-2-iphone-8-plus.png")
}
}
You can set the contentMode either in the storyboard or in viewDidLoad. You don't need to keep setting it after updating an image.
let myBackgroundImage = UIImageView (frame: CGRect.zero)
override func viewDidLoad() {
super.viewDidLoad()
myBackgroundImage.image = UIImage(named: "wallpaper-1-iphone-8-plus.png")
myBackgroundImage.contentMode = UIViewContentMode.scaleAspectFill
self.view.addSubview(myBackgroundImage)
}
#IBAction func ButtonPressed(_ sender: Any) {
myBackgroundImage.image = UIImage(named: "wallpaper-2-iphone-8-plus.png")
}
there was a question like this already made but I tried the suggestions and it didn't work for me still. :/
I am trying to make a quiz app using this tutorial: https://www.youtube.com/watch?v=KNAQ3Y8PGkM&t=1s
Here is a link to download my project: https://www.dropbox.com/s/bwvg6fyrrzudued/kat%20quiz.zip?dl=0
Everything is perfect except I get the error:
Could not cast value of type 'UIView' (0x10d54a4c0) to 'UIButton' (0x10d552120)
I'd really appreciate some help. I tried everything in my knowledge and searching, thank you. :)
import UIKit
class ViewController: UIViewController {
let questions = ["What color is Courage the Cowardly Dog?", "What is the name of the woman that lives with Courage?", "What is the name of the man that lives with Courage?"]
let answers = [["Purple","Grey","Orange"],["Muriel", "Angela", "Elizabeth"], ["Eustace", "Robert", "Ezio"]]
//Variables
var currentQuestion = 0
var rightAnswerPlacement:UInt32 = 0
var points = 0
//Label
#IBOutlet weak var lbl: UILabel!
//Button
#IBAction func action(_ sender: AnyObject) {
if (sender.tag == Int(rightAnswerPlacement))
{
print ("RIGHT!")
points += 1
}
else
{
print ("WRONG!!!!!!")
}
if (currentQuestion != questions.count)
{
newQuestion()
}
else{
performSegue(withIdentifier: "showScore", sender: self)
}
}
override func viewDidAppear(_ animated: Bool) {
newQuestion()
}
//Function that displays new question
func newQuestion(){
lbl.text = questions[currentQuestion]
rightAnswerPlacement = arc4random_uniform(3)+1
//Create a button
var button:UIButton = UIButton()
var x = 1
for i in 1...3
{
//Create a button
button = view.viewWithTag(i) as! UIButton
if (i == Int(rightAnswerPlacement))
{
button.setTitle(answers[currentQuestion][0], for: .normal)
}
else
{
button.setTitle(answers[currentQuestion][x], for: .normal)
x = 2
}
}
currentQuestion += 1
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Did you create UI Button in your Story Board ??
In your youtube video, watch 1:45
And remember to set your 3 UI Button's tag to 1, 2 and 3
watch 3:20
Your problem occurs because you've set your View's tag = 1.
You can fix it easily by change View's tag value to a number != 1, 2 and 3
Because your ViewController have 2 view with the same tag = 1. (view and UI Button).
So when you use view.viewWithTag(i), It accidentally select view not UI Button. So it can not convert to UI Button type
P/s: next time, if you want to select your Button directly, you can make an #IBOutlet for that Button as you make with your Label. It will not cause confusing error like that
Just messing around with a simple iOS app in Swift that displays an image view and segmented control underneath with 3 options. I'm just trying to get the image to swap out based on which option is chosen from the segmented control. I have this simple code so far:
class ViewController: UIViewController {
var gallery = ["apple", "banana", "coconut"]
#IBOutlet weak var imageView: UIImageView!
#IBAction func changeSegment(sender: AnyObject) {
let segmentedControl = sender as? UISegmentedControl
if let index = segmentedControl?.selectedSegmentIndex {
imageView.image = UIImage(named: gallery[index])
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
I keep running into an error that prints out "(lldb)". It looks like it hits a breakpoint at:
let segmentedControl = sender as? UISegmentedControl
not sure why. Any and all help is greatly appreciated!
You have a breakpoint on the side of your code. I would clean your file and run.
I've been trying to animate a GIF in Swift but it just doesn't work. I think I found a way but there's an error, please help.
Here's the code:
#IBOutlet var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// (Here is the error it states "Cannot assign a value of type '[UIImage?]' to a value of type '[UIImage]?'")
imageView.animationImages = [
UIImage(named: "logo1.jpg"),
UIImage(named: "logo2.jpeg"),
UIImage(named: "logo3.png")
]
imageView.animationDuration = 3
imageView.startAnimating()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
// ...
}
You may run gif files directly, follow the links below;
https://github.com/kaishin/gifu
How to load GIF image in Swift?
As far as the issue in you code is, as already 'Leo Dabus' pointed out, is you are not un-wrapping the UIImage instances. Try same code with the following modifications.
imageView.animationImages = [
UIImage(named: "logo1.jpg")!, //File Extension would not be required if .png
UIImage(named: "logo2.jpeg")!, //File Extension would not be required if .png
UIImage(named: "logo3.png")!
]
imageView.animationDuration = 3
imageView.startAnimating()
You just need to unwrap the optional UIImage returned by UIImage(named:) method. Try like this:
class ViewController: UIViewController {
#IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
imageView.animationImages = [
UIImage(named: "logo1")!,
UIImage(named: "logo2")!,
UIImage(named: "logo3")!]
imageView.animationDuration = 3
imageView.startAnimating()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
I have created one example for you.
Here is code:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
imageView.animationImages = [
UIImage(named: "1")!,
UIImage(named: "2")!,
UIImage(named: "3")!,
UIImage(named: "4")!,
UIImage(named: "5")!,
UIImage(named: "6")!,
UIImage(named: "7")!,
UIImage(named: "8")!,
UIImage(named: "9")!,
UIImage(named: "10")!,
UIImage(named: "11")!,
UIImage(named: "12")!
]
imageView.animationDuration = 3
imageView.startAnimating()
}
}
You can see Result HERE.
And HERE is sample project.
Absolute Swift beginner here.
I have been trying to get a simple set of png's to animate.
Here is what I have:
Any help would be much appreciated.
Thanks
#import <UIKit/UIKit.h>
class ViewController: UIViewController {
#IBOutlet var myImageView : UIImageView
#IBOutlet var animationBtn : UIButton
var imageList = UIImage[]()
#IBAction func animationBtnClicked(sender : AnyObject) {
startAnimation()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
for i in 1...13
{
let imageName = "\(i)"
imageList += UIImage(named: imageName)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func startAnimation() -> Void
{
if !myImageView.isAnimating()
{
myImageView.animationImages = imageList
myImageView.startAnimating()
animationBtn.setTitle("Stop Animation", forState: UIControlState.Normal)
} else
{
myImageView.stopAnimating()
myImageView.image = UIImage(named:"bomb.jpg")
animationBtn.setTitle("Start Animation", forState: UIControlState.Normal)
}
}
}
Here is the adjusted code if it helps anyone.
Cheers
import UIKit
class ViewController: UIViewController {
#IBOutlet var myImageView: UIImageView!
#IBOutlet var animationBtn: UIButton!
var imageList = [UIImage]()
#IBAction func animationBtnClicked(sender: AnyObject) {
startAnimation()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
for i in 1...99
{
let imageName = "\(i)"
imageList.append(UIImage(named: imageName)!)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func startAnimation() -> Void
{
myImageView.animationImages = imageList
myImageView.startAnimating()
}
}
Those errors messages shows the exact issue.
Issue 1
For fixing has no initializers, you need implement at-least one init function in your class.
Issue 2
For fixing IBOutlet has non-optional, you need to change your IBOutlet variables to optionals.
#IBOutlet var myImageView : UIImageView!
#IBOutlet var animationBtn : UIButton!
Issue 3
For fixing that [UIImage] is not identical to UInt8. The += can't be used to append a single UIImage to [UIImage]
You need to change:
imageList += UIImage(named: imageName)
to
imageList.append(UIImage(named: imageName))