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.
Related
I have a UIViewController with 2 UITextFields and 1 UIImageView (the image is optional)
When I click Save I want to save all values in an array of objects. But the image (selectedImage) is not mandatory.
The issue is with the UIImage because is asking me for an optional value for the UIImage if I don't have an image. And I don't know what to assign because I don't want to have any image in my array if the user did't picked a picture. And I've tried to put a NIL value but is not working.
Here is my code for Model:
import Foundation
import UIKit
class RoadsideDefect {
var vehicleReg: String
var detailsDefect: String
var imagesDefect: [UIImage]?
init(vehicleRegistration: String, detailsOfDefect: String, imagesOfDefects: [UIImage]?) {
self.vehicleReg = vehicleRegistration
self.detailsDefect = detailsOfDefect
self.imagesDefect = imagesOfDefects
}
}
Here is the code in the Controller:
var vehicleReg = ""
var detailsDefect = ""
var imagesDefect: [UIImage]? = [UIImage]()
var roadsideDefect: [RoadsideDefect] = []
//MARK: Save button tapped
#IBAction func saveBtnTapped(_ sender: UIBarButtonItem) {
guard let vehicleRegText = vehicleRegTextfieldOutlet.text, !vehicleRegText.isBlank else {
showAlertWithTitle(title: "Error", message: "Please add vehicle reg number.")
return
}
guard let detailsText = detailsTextfieldOutlet.text, !detailsText.isBlank else {
showAlertWithTitle(title: "Error", message: "Please add some details.")
return
}
let selectedImage: UIImage? = roadsideDefectImageView?.image
vehicleReg = vehicleRegText
detailsDefect = detailsText
// ISSUE HERE
UIImageWriteToSavedPhotosAlbum(selectedImage ?? HowToSetItNilOrEmpty?, self, #selector(self.image(_:didFinishSavingWithError:contextInfo:)), nil)
roadsideDefect.append(RoadsideDefect(vehicleRegistration: vehicleReg, detailsOfDefect: detailsDefect, imagesOfDefects: imagesDefect))
print(roadsideDefect)
}
I marked the issue with a comment.
if let image = selectedImage {
UIImageWriteToSavedPhotosAlbum(image, self, #selector(self.image(_:didFinishSavingWithError:contextInfo:)), nil)
}
You can use optional binding for unwrapping optionals.
guard let imageView = roadsideDefectImageView else { return }
guard let image = imageView.image else { return }
UIImageWriteToSavedPhotosAlbum(image, self, #selector(self.image(_:didFinishSavingWithError:contextInfo:)), nil)
I'm trying to make a choose-your-own adventure game that changes the text of two labels (the user choices) depending on which label the user taps. I figured I would just do a very nested if-else statement rather than bother with trying to implement a binary tree. I know how to attach the gesture recognizer to a label (I think):
let tapped1 = UITapGestureRecognizer(target: self, action: #selector(VCGame.usrChose1))
choice1.isUserInteractionEnabled = true
choice1.addGestureRecognizer(tapped1)
let tapped2 = UITapGestureRecognizer(target: self, action: #selector(VCGame.usrChose2))
choice2.isUserInteractionEnabled = true
choice2.addGestureRecognizer(tapped2)
and I can define what to do when the label is touched in the usrChose1 and usrChose2 functions, however, those functions only work once: the first time the function is chosen and my game has more than just one choice. From there, the labels will just do the same thing if the user touches them.
How would I go about having a condition inside the if-else statement that evaluates to true or false if label1 or label2 is tapped?
Here's the code for usrChoice1 and usrChoice2, for clarification
func usrChose1(sender : UITapGestureRecognizer) {
print("tap 1 working")
choice1.text = "choice1.1"
choice2.text = "choice1.2"
}
func usrChose2(sender : UITapGestureRecognizer) {
print("tap2 working")
choice1.text = "update2.1";
choice2.text = "update2.2"
}
Below image shows my requirement :
According to your requirement, I have tried the following:
I have made a dummy project with two labels inside a view controller
ViewController.swift
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var choice1Label: UILabel!
#IBOutlet weak var choiceLabel2: UILabel!
var tapStart: Bool = false
var levelType1: Level?
var levelType2: Level?
override func viewDidLoad() {
super.viewDidLoad()
let tapped1 = UITapGestureRecognizer(target: self, action: #selector(usrChose1))
choice1Label.isUserInteractionEnabled = true
choice1Label.addGestureRecognizer(tapped1)
let tapped2 = UITapGestureRecognizer(target: self, action: #selector(usrChose2))
choiceLabel2.isUserInteractionEnabled = true
choiceLabel2.addGestureRecognizer(tapped2)
setup()
}
var currentLevel1: Level?
var currentLevel2: Level?
func setup() {
let lb2Child1Child1 = Level(text: "2.1.1", subLevels: nil)
let lb2Child1Child2 = Level(text: "2.1.2", subLevels: nil)
let lb1Child1Child1 = Level(text: "1.1.1", subLevels: nil)
let lb1Child1Child2 = Level(text: "1.1.2", subLevels: nil)
let lb1Child2Child1 = Level(text: "1.2.1", subLevels: nil)
let lb1Child2Child2 = Level(text: "1.2.2", subLevels: nil)
let lb1Child1 = Level(text: "1.1", subLevels: [lb1Child1Child1, lb1Child1Child2])
let lb1Child2 = Level(text: "1.2", subLevels: [lb1Child2Child1, lb1Child2Child2])
let lb2Child1 = Level(text: "2.1", subLevels: [lb2Child1Child1, lb2Child1Child2])
let lb2Child2 = Level(text: "2.2", subLevels: nil)
levelType1 = Level(text: "1", subLevels: [lb1Child1, lb1Child2])
levelType2 = Level(text: "2", subLevels: [lb2Child1, lb2Child2])
choice1Label.text = levelType1!.text ?? ""
choiceLabel2.text = levelType2!.text ?? ""
}
func usrChose1(sender : UITapGestureRecognizer) {
if !tapStart {
currentLevel1 = levelType1
tapStart = true
}
if let subLevelsArray = currentLevel1?.subLevels {
print(subLevelsArray[0].text ?? "")
print(subLevelsArray[1].text ?? "")
choice1Label.text = subLevelsArray[0].text ?? ""
choiceLabel2.text = subLevelsArray[1].text ?? ""
currentLevel1 = subLevelsArray[0]
currentLevel2 = subLevelsArray[1]
}
}
func usrChose2(sender : UITapGestureRecognizer) {
//print("tap2 working")
// choice1Label.text = "update2.1";
//choiceLabel2.text = "update2.2"
if !tapStart {
currentLevel2 = levelType2
tapStart = true
}
if let subLevelsArray = currentLevel2?.subLevels {
print(subLevelsArray[0].text ?? "")
print(subLevelsArray[1].text ?? "")
choice1Label.text = subLevelsArray[0].text ?? ""
choiceLabel2.text = subLevelsArray[1].text ?? ""
currentLevel1 = subLevelsArray[0]
currentLevel2 = subLevelsArray[1]
}
}
}
I have made a class named Level to represent a single level and each level contains sublevels
Level.swift
import UIKit
class Level {
var text: String?
var subLevels: [Level]?
init(text: String, subLevels: [Level]?) {
self.text = text
self.subLevels = subLevels ?? nil
}
}
You have to add UITapGestureRecognizer in UILabel or UIView whatever is container.
Add 2 different Int variables in each functions usrChose1 and usrChose2 respectively, which will be work as a counter.
var i = 0
var j = 0
func usrChose1(_ recognizer: UITapGestureRecognizer) {
i++
print("Total clicked label 1 :::",i)
}
func usrChose2(_ recognizer: UITapGestureRecognizer) {
j++
print("Total clicked label 2 :::",j)
}
So I am creating a card game, Ring of Fire. I have stored images like this:
var picture:[UIImage] = [
UIImage(named: "Card2")!,
UIImage(named: "Card3")!,
UIImage(named: "Card4")!,
UIImage(named: "Card5")!,
UIImage(named: "Card6")!,
UIImage(named: "Card7")!,
UIImage(named: "Card8")!,
UIImage(named: "Card9")!,
UIImage(named: "Card10")!,
UIImage(named: "CardJack")!,
UIImage(named: "CardQueen")!,
UIImage(named: "CardKing")!,
UIImage(named: "CardAce")!,
]
Each card has text displayed under the current card:
var name:String = ""
var files = ["Velg en som må drikke", // 2
"Drikk selv", // 3
"Alle jenter må drikke", // 4
"Tommelen", // 5
"Alle gutter må drikke", // 6
"Pek på himmelen", // 7
"Drikkepartner", // 8
"Rim", // 9
"Kategori", // 10
"Lag en regel", // Jack
"Spørsmålsrunde", // Queen
"Hell drikke i koppen", // King
"Fossefall"] // Ace
And this is how I pick a random card:
func imageTapped(img: AnyObject){
if(cardsleftLabel.text != "0") {
let randomNumber = Int(arc4random_uniform(UInt32(files.count)))
let image = picture[randomNumber]
cardImage.image = image
name = files[randomNumber]
}
else{
print("No more cards")
}
}
The problem is that the card may appear many times, and that is wrong. There are 4 of each card, so how can I control that in my game? So the CardJack don't appear 6 times?
One way to do it is to generate an array of indices that represent your cards. Shuffle that array, and then remove the indices from that array as you draw a card.
// generate random list of indices from 0...12 four each
var cardIndices = (0...51).map {($0 % 13, arc4random())}.sort{$0.1 < $1.1}.map{$0.0}
// To get a card, remove last card from deck
let last = cardIndices.removeLast()
// use the index to look up the picture
let randomCard = picture[last]
// It's also easy to check how many cards you have left in your deck
let remaining = cardIndices.count
This works by first creating an array of tuples which contain a number from 0...12 and a some random integer. Then that array is sorted by the random integer element in the tuple, and then map is used to separate out just the array of indices leaving you with a random array of Int with values from 0...12 (four values of each).
Here it is in class form.
import UIKit
struct Card {
let image: UIImage
let text: String
}
class Deck {
private let cards:[Card] = [
Card(image: UIImage(named: "Card2")!, text: "Velg en som må drikke"),
Card(image: UIImage(named: "Card3")!, text: "Drikk selv"),
Card(image: UIImage(named: "Card4")!, text: "Alle jenter må drikke"),
Card(image: UIImage(named: "Card5")!, text: "Tommelen"),
Card(image: UIImage(named: "Card6")!, text: "Alle gutter må drikke"),
Card(image: UIImage(named: "Card7")!, text: "Pek på himmelen"),
Card(image: UIImage(named: "Card8")!, text: "Drikkepartner"),
Card(image: UIImage(named: "Card9")!, text: "Rim"),
Card(image: UIImage(named: "Card10")!, text: "Kategori"),
Card(image: UIImage(named: "CardJack")!, text: "Lag en regel"),
Card(image: UIImage(named: "CardQueen")!, text: "Spørsmålsrunde"),
Card(image: UIImage(named: "CardKing")!, text: "Hell drikke i koppen"),
Card(image: UIImage(named: "CardAce")!, text: "Fossefall")
]
private var cardIndices = [Int]()
var cardsInDeck: Int { return cardIndices.count }
func shuffleCards() {
cardIndices = (0...51).map{($0 % 13, arc4random())}.sort{$0.1 < $1.1}.map{$0.0}
}
func drawCard() -> Card {
if cardIndices.count == 0 {
shuffleCards()
}
let last = cardIndices.removeLast()
return cards[last]
}
}
Notes:
The cards and cardIndices have been made private to hide those details from a user of Deck.
Thanks to #Paulw11's suggestion, this solution now uses a struct to represent a card. This keeps the data together and provides a nice value that can be returned from drawCard.
The user of a Deck can create a Deck with Deck(), they can call shuffleCards() to randomize the deck, check the cardsInDeck property to find out how many shuffled cards are available, and they can call drawCard() to get the next card from the deck.
How to Use
For the viewController that controls the deck, add a property to the viewController:
class MyGame: UIViewController {
var deck = Deck()
// the rest of the code
}
Then when you need a card, for example inside of an #IBAction for a button, just call deck.drawCard:
#IBAction func turnOverNextCard(button: UIButton) {
let card = deck.drawCard()
// Use the image and text to update the UI
topCardImageView.image = card.image
topCardLabel.text = card.text
// I'm not going to wait for the deck to shuffle itself
if deck.cardsInDeck < 10 {
deck.shuffleCards()
}
}
Splitting Hairs: A Better Shuffle
My shuffle routine shuffles the deck by associating a random UInt32 with each card and then sorting the deck by those values. If the same random number is generated for two cards, then it is possible that earlier cards in the deck would be favored over later cards (or vice versa depending on the sort algorithm). This is really splitting hairs, but in the interest of providing the best shuffle possible, I provide the following alternative:
func shuffleCards() {
cardIndices = (0...51).map {$0 % 13}
for i in (1...51).reverse() {
let rand = Int(arc4random_uniform(UInt32(i + 1)))
(cardIndices[i], cardIndices[rand]) = (cardIndices[rand], cardIndices[i])
}
}
This algorithm is based upon the Fisher-Yates shuffle.
You need a class to represent the Deck of cards, like this.
class Deck {
static let seeds = 4
var images : [UIImage:Int] = [
UIImage(named: "Card2")! : seeds,
UIImage(named: "Card3")! : seeds,
UIImage(named: "Card4")! : seeds,
UIImage(named: "Card5")! : seeds,
UIImage(named: "Card6")! : seeds,
UIImage(named: "Card7")! : seeds,
UIImage(named: "Card8")! : seeds,
UIImage(named: "Card9")! : seeds,
UIImage(named: "Card10")! : seeds,
UIImage(named: "CardJack")! : seeds,
UIImage(named: "CardQueen")! : seeds,
UIImage(named: "CardKing")! : seeds,
UIImage(named: "CardAce")! : seeds
]
func extractRandomCard() -> UIImage? {
let flatten = images.reduce([UIImage]()) { [UIImage](count: $0.1.1, repeatedValue: $0.1.0) }
guard !flatten.isEmpty else { return nil }
let random = Int(arc4random_uniform(UInt32(flatten.count)))
let selectedCard = flatten[random]
images[selectedCard] = images[selectedCard]! - 1
return selectedCard
}
}
Now you can extract cards from the deck writing
let deck = Deck()
let image = deck.extractRandomCard()
Each time you extract a card the Deck keeps track of it and it won't let you extract more than 4 times the same card.
I didn't test it... but it should work
An alternative approach to the random-stuff is to use some of Apple's nice GamePlayKit-stuff created exactly for these kind of use-cases. If you have the cards array you could for instance just do:
let shuffled2 = GKRandomSource().arrayByShufflingObjectsInArray(cards) as! [Card]
or you could keep the array unshuffled and instead shuffle the indexes you request:
let indexes = GKShuffledDistribution.init(forDieWithSideCount: 52)
// going through all the cards randomly
for _ in cards {
let card = cards[indexes.nextInt()]
}
public enum Palo: Int
{
case Corazones = 1
case Treboles = 2
case Picas = 3
case Diamantes = 4
}
public struct Card
{
public var text: String
public var position: Int
public var palo: Palo
public func description() -> String
{
return "\(self.position) of \(self.palo) -- \(self.text)"
}
}
public struct Deck
{
public var cards: [Card]
public init()
{
cards = [Card]()
for number in 1...13
{
for palo in 1...4
{
let card: Card = Card(text: "", position: number, palo: Palo(rawValue: palo)!)
cards.append(card)
}
}
}
/**
Return cards one by one
*/
public mutating func randomCard() -> Card?
{
guard !self.cards.isEmpty else
{
return nil
}
let position: Int = Int(arc4random_uniform(UInt32(self.cards.count)))
let card: Card = self.cards.removeAtIndex(position)
return card
}
}
//
// TEST
//
var deck: Deck = Deck()
for index in 1...200
{
if let card = deck.randomCard()
{
print("\(index) -- \(card.description())")
}
}
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
}
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.