Randomly select a UIImage - ios

I need to pick one of these dots. I add them all before viewDidLoad, I need it to pick a random one. My current code returns the error cannot assign to 'openingScreenDynamicDot in 'self'. How is this fixed?
CODE:
let openingScreenDynamicDot = UIImage()
let dotOne = UIImage(named: "dot1.png")
let dotTwo = UIImage(named: "dot2.png")
let dotThree = UIImage(named: "dot3.png")
let dotFour = UIImage(named: "dot4.png")
let dotFive = UIImage(named: "dot5.png")
let dotSix = UIImage(named: "dot6.png")
let dotSeven = UIImage(named: "dot7.png")
let dotEight = UIImage(named: "dot8.png")
let dotNine = UIImage(named: "dot9.png")
let dotTen = UIImage(named: "dot10.png")
let dotEleven = UIImage(named: "dot11.png")
let dotTwelve = UIImage(named: "dot12.png")
let dotThirteen = UIImage(named: "dot13.png")
var imageNumber = arc4random()%13
override func viewDidLoad() {
let theRandomImages = [dotOne, dotTwo, dotThree, dotFour, dotFive, dotSix, dotSeven, dotEight, dotNine, dotTen, dotEleven, dotTwelve, dotThirteen]
openingScreenDynamicDot = theRandomImages.objectAtIndex(imageNumber)
}

You declare constants with the let keyword and variables with the var keyword.
So change let openingScreenDynamicDot to var openingScreenDynamicDot
also, a swift native array does not have a objectAtIndex method so..
change
openingScreenDynamicDot = theRandomImages.objectAtIndex(imageNumber)
to
openingScreenDynamicDot = theRandomImages[imageNumber]

You can try this code to generate one of your random "dots".
override func viewDidLoad(){
let openingScreenDynamicDot.image = UIImage(named: "dot\(arc4random_uniform(13) + 1).png")
}
This is called "String Interpolation". For more info, Click here.
I hope this can help you if you are still having problems.

Related

Swift 5 or up - Image view on pickerview

My images from "2.jpg" to "7.jpg" shows but the first image("1.jpg") on my simulator. what do I need to change?
var imageFileName = ["1.jpg","2.jpg","3.jpg","4.jpg","5.jpg","6.jpg","7.jpg"]
for i in 0 ..< MAX_ARRAY_NUM {
let image = UIImage(named: imageFileName[i])
imageArray.append(image)
lblImageFileName.text = imageFileName[0]
imageView.image = imageArray[0]
enter image description here
enter image description here
I think you should change below two lines
lblImageFileName.text = imageFileName[0]
imageView.image = imageArray[0]
to,
lblImageFileName.text = imageFileName[i]
imageView.image = imageArray[i]
as you used variable i to represent index

How to display an image if variable equals a special number using swift 3?

I have three pictures (lvl1.png, lvl2.png, lvl3.png) and an variable (let level = 1). What should I do to display an image named 'lvl2' if level = 2, and when level = 3 I need to show the last image (lvl3.png)?
you can use:
let image = UIImage(named: "lvl\(level).png")
or
let image: UIImage!
switch level {
case 1:
image = UIImage(named: "lvl1.png")
case 2:
image = UIImage(named: "lvl2.png")
case 3:
image = UIImage(named: "lvl3.png")
default:
image = UIImage()
}
avatar.image = image
you can try
imgName = "lvl" + String(lavel)
imageView.image = UIImage(named: imgName)
Another alternative is to create a method that returns an image, like so:
func imageFor(level: Int) -> UIImage? {
let image = UIImage(named: "lvl\(currentLevel)")
return image
}
Usage:
var currentLevel = 1
let image = imageFor(level: currentLevel)
You can try
var level = 1 {
didSet {
self.imageview.image = UIImage(named: "lvl\(level)")
}
}
when you change the level the imageView will change automatically

How to link an image to a sound randomly?

I have this code and it's working, but not as really want to. I'm new to Xcode/Swift/developing apps. I've made it watching tutorials and using some snippets as examples, but so far is working :)
I'd like to make it work in this way:
When I click on playSound and hear it, then I have to choose between leftImage and rightImage..the image that matches with the playSound. I've tried into many ways to get it work.. but nothing...I cannot make the sound index a string to compare as "if a == b .."
When I open the app, it shows me only two bottom buttons.. but not any image. How can I make it to show the first image?
I also like to make it a bit random think... When I click on "nextImage" button, I'd like to shows to different images but only one linked to the sound..so when I play the sound..had to check only the photo who matches with the sound.
At this moment, I have only 8 photos/sounds into the array, but when I click more than 9 times on nextImage.. the images are going on and on.. but the sound starts from beginning and it's not linked any more. for example, at the 10th image..it playSound says it's at 1. How can I make It to follow the image index?
How to convert the image index into text? for example, if its shows me the image "foto1"; I'd like to show me under the image a text in the label.
import UIKit
import AVFoundation
class ViewController: UIViewController {
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.
}
var soundFiles: [String] = [
"s0",
"s1",
"s2",
"s3",
"s4",
"s5",
"s6",
"s7",
"s8",
"s9"
]
var images1: [UIImage] = [
UIImage(named: "foto1.png")!,
UIImage(named: "foto2.png")!,
UIImage(named: "foto3.png")!,
UIImage(named: "foto4.png")!,
UIImage(named: "foto5.png")!,
UIImage(named: "foto6.png")!,
UIImage(named: "foto7.png")!,
UIImage(named: "foto8.png")!
]
var images2: [UIImage] = [
UIImage(named: "foto1.png")!,
UIImage(named: "foto2.png")!,
UIImage(named: "foto3.png")!,
UIImage(named: "foto4.png")!,
UIImage(named: "foto5.png")!,
UIImage(named: "foto6.png")!,
UIImage(named: "foto7.png")!,
UIImage(named: "foto8.png")!
]
var happySad: [UIImage] = [
UIImage(named: "sad.png")!,
UIImage(named: "happy.png")!
]
var currentImageIndex = 0
var currentImage2Index = 0
#IBOutlet weak var leftImage: UIImageView!
#IBOutlet weak var rightImage: UIImageView!
#IBOutlet weak var sh: UIImageView!
#IBAction func nextImages(_ sender: Any) {
currentImageIndex += 1
let numberOfImages = images1.count
let nextImage1Index = currentImageIndex % numberOfImages
leftImage.image = images1[nextImage1Index]
leftImage.isUserInteractionEnabled = true
self.view.addSubview(leftImage)
let gesture1 = UITapGestureRecognizer(target: self, action: #selector(ViewController.singleTap1))
leftImage.addGestureRecognizer(gesture1)
currentImage2Index += 1
let numberOfImages2 = images2.count
let nextImage2Index = currentImage2Index % numberOfImages2
rightImage.image = images2[nextImage2Index]
sh.image = UIImage(named: "question")
rightImage.isUserInteractionEnabled = true
self.view.addSubview(rightImage)
let gesture2 = UITapGestureRecognizer(target: self, action: #selector(ViewController.singleTap2))
rightImage.addGestureRecognizer(gesture2)
}
func singleTap1() {
if currentImageIndex == currentImage2Index {
sh.image = UIImage(named: "happy.png")
print("ok")
} else {
sh.image = UIImage(named: "sad.png")
print("not ok")
}
}
func singleTap2() {
if currentImageIndex == currentImage2Index {
sh.image = UIImage(named: "happy.png")
print("ok2")
} else {
sh.image = UIImage(named: "sad.png")
print("not ok2")
}
}
var player: AVAudioPlayer!
#IBAction func playSound(_ sender: Any) {
let numberOfImages = images1.count
let nextImage5Index = currentImageIndex % numberOfImages
let soundFilePath = Bundle.main.url(forResource: soundFiles[nextImage5Index], withExtension: ".m4a")!
player = try! AVAudioPlayer(contentsOf: soundFilePath)
player.prepareToPlay()
player.play()
}
}
I think you are over complicating the issue.
I would personally create a struct that contains each 'level' of the game.
enum correctImageType {
case left, right
}
struct Level {
var word: String
var leftImage: UIImage
var rightImage: UIImage
var soundFile: String
var correctImage: correctImageType
}
var level1 = Level(word: "Dog", leftImage: UIImage(named: "dog"), rightImage: UIImage(named: "cat", soundFile: "Woof", correctImage: .left)
This gives you enough information in one data structure to display each level. You can then create an array of these items, sort them, random sort them, mark as complete as each is done etc.
There are alot of questions within your question. I would try to make it more specific and tackle one particular part of the problem at a time. There is no problem in posting multiple questions as long as they are different.

Change view in tab bar controller

I have some problem at creating programmatically tab bar. I create class where create tab bar:
override func viewWillAppear(animated: Bool) {
let mondayTab = MondayTableViewController()
mondayTab.tabBarItem.title = "Monday"
mondayTab.tabBarItem.image = UIImage(named: "")
let tuesdayTab = TuesdayTableViewController()
tuesdayTab.tabBarItem.title = "Tuesday"
tuesdayTab.tabBarItem.image = UIImage(named: "")
let wednesdayTab = WednesdayTableViewController()
wednesdayTab.tabBarItem.title = "Wednesday"
wednesdayTab.tabBarItem.image = UIImage(named: "")
let thursdayTab = TuesdayTableViewController()
thursdayTab.tabBarItem.title = "Thursday"
thursdayTab.tabBarItem.image = UIImage(named: "")
let fridayTab = TuesdayTableViewController()
fridayTab.tabBarItem.title = "Friday"
fridayTab.tabBarItem.image = UIImage(named: "")
let tabBarController = [mondayTab, tuesdayTab, wednesdayTab, thursdayTab, fridayTab]
self.viewControllers = tabBarController
}
In viewDidLoad I try to change starting view, using something like this:
tabBarController?.selectedIndex = 1
but it not working...

How to generate random image using image view in swift

I just followed treehouse course and create my first Fun Fact app.In that they generate a random array quotes.
Needed:
I have placed image view using storyboard.Already when pressing one button random array quotes will generate.But i need when that same button pressed a random image should generate.I am new to swift .!
This is factbook.swift
struct FactBook {
// stored in arry to show all quotes
let factsArray = [
"You have to dream before your dreams can come true.",
"To succeed in your mission, you must have single-minded devotion to your goal.",
"You have to dream before your dreams can come true.",
"Love your job but don’t love your company, because you may not know when your company stops loving you.",
"Failure will never overtake me if my definition to succeed is strong enough.",
]
//make a random quote
func randomFact() -> String {
//
// let unsignedRandomNumber = arc4random_uniform(unsignedArrayCount)
//
let unsignedArrayCount = UInt32(factsArray.count)
let unsignedRandomNumber = arc4random_uniform(unsignedArrayCount)
let randomNumber = Int(unsignedRandomNumber)
//
// let unsignedRandomNumber = arc4random_uniform(unsignedArrayCount)
// let randomNumber = Int(signedRandomNumber)
return factsArray[randomNumber]
}
}
This is viewcontroller.swift
class ViewController: UIViewController {
#IBOutlet weak var funFactLabel: UILabel!
#IBOutlet weak var funFactButton: UIButton!
#IBOutlet weak var imgV: UIImageView!
let factBook = FactBook()
let colorWheel = ColorWheel()
//method to define
// let yourImage = UIImage(named: "apj")
// let imageview = UIImageView(image: yourImage)
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
funFactLabel.text = factBook.randomFact()
self.view.backgroundColor = UIColor(patternImage: UIImage(named: "apj")!)
// let yourImage = UIImage(named: "apj")
// let imageview = UIImageView(image: yourImage)
// self.view.addSubview(imageview)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func showFunFact() {
let randomColor = colorWheel.randomColor()
view.backgroundColor = randomColor
funFactButton.tintColor = randomColor
//funFactButton.tintColor = clearcolor
funFactLabel.text = factBook.randomFact()
}
}
The solution mainly is to use the same approach you have done with the random text. So to sum up, you should have an array of the images, and a function to select a random image. Then call that function from your view controller. A possible implementation to this approach is:
Add this array to your FactBook
let factsImagesArray = [
"image1.png",
"image2.png",
"image3.png",
"image4.png",
"image5.png",
]
Add this method to your FactBook
func randomFactImage() -> UIImage {
let unsignedArrayCount = UInt32(factsImageArray.count)
let unsignedRandomNumber = arc4random_uniform(unsignedArrayCount)
let randomNumber = Int(unsignedRandomNumber)
return UIImage(named: factsImageArray[randomNumber])!
}
and in your viewcontroller change showFunFact to:
#IBAction func showFunFact() {
let randomColor = colorWheel.randomColor()
view.backgroundColor = randomColor
funFactButton.tintColor = randomColor
funFactLabel.text = factBook.randomFact()
imgV.image = faceBook.randomFactImage()
}
Ofc you should have the image1.png, image2.png ... in your resources
#IBAction func randomimage(sender: AnyObject)
{
//list of Images in array
let image : NSArray = [ UIImage(named: "1.jpg")!,
UIImage(named: "2.jpg")!,
UIImage(named: "3.jpg")!,
UIImage(named: "4.jpg")!,
UIImage(named: "5.jpg")!,
UIImage(named: "6.jpg")!,
UIImage(named: "7.jpg")!]
//random image generating method
let imagerange: UInt32 = UInt32(image.count)
let randomimage = Int(arc4random_uniform(imagerange))
let generatedimage: AnyObject = image.objectAtIndex(randomimage)
self.myimage.image = generatedimage as? UIImage
}

Resources