Random Numbers in Swift - ios

I would like to create random numbers to be displayed in 5 UIImage boxes on the front of the app. However, I would like those numbers to not always be in the same range. For instance, my code below shows 0 ... 9 for randomPoolBallIndex3. But instead, I would like it to show any number from 0 ... 49 but not duplicate the same number on the other randomPoolBallIndex's. So every time the button is pressed it will not display, let's say 1, 1, 34, 35 and 50, but instead each number will be different.
Is there a way to pull this off?
I broke the array down from 0 ... 49 for each randomPoolBallIndex's but now they will only display what I have set the ranges for and I am not entirely happy, while it has resolved the duplication problem.
Code Below:
let ballArray = ["poolball1","poolball2","poolball3","poolball4","poolball5","poolball6","poolball7","poolball8","poolball9","poolball10","poolball11","poolball12","poolball13","poolball14","poolball15","poolball16","poolball17","poolball18","poolball19","poolball20","poolball21","poolball22","poolball23","poolball24","poolball25","poolball26","poolball27","poolball28","poolball29","poolball30","poolball31","poolball32","poolball33","poolball34","poolball35","poolball36","poolball37","poolball38","poolball39","poolball40","poolball41","poolball42","poolball43","poolball44","poolball45","poolball46","poolball47","poolball48","poolball49","poolball50"]
var randomPoolBallIndex: Int = 0
var randomPoolBallIndex1: Int = 0
var randomPoolBallIndex2: Int = 0
var randomPoolBallIndex3: Int = 0
var randomPoolBallIndex4: Int = 0
var randomPoolBallIndex5: Int = 0
#IBOutlet weak var poolBallView1: UIImageView!
#IBOutlet weak var poolBallView2: UIImageView!
#IBOutlet weak var poolBallView3: UIImageView!
#IBOutlet weak var poolBallView4: UIImageView!
#IBOutlet weak var poolBallView5: UIImageView!
#IBAction func buttonPressed(_ sender: UIButton) {
randomPoolBallIndex1 = Int.random(in: 20 ... 29)
randomPoolBallIndex2 = Int.random(in: 40 ... 49)
randomPoolBallIndex3 = Int.random(in: 0 ... 9)
randomPoolBallIndex4 = Int.random(in: 30 ... 39)
randomPoolBallIndex5 = Int.random(in: 10 ... 19)
poolBallView1.image = UIImage(named: ballArray[randomPoolBallIndex1])
poolBallView2.image = UIImage(named: ballArray[randomPoolBallIndex2])
poolBallView3.image = UIImage(named: ballArray[randomPoolBallIndex3])
poolBallView4.image = UIImage(named: ballArray[randomPoolBallIndex4])
poolBallView5.image = UIImage(named: ballArray[randomPoolBallIndex5])

Using Shuffled
I suppose you just need to get 5 different random pool ball names from your ballArray. So you don't need to generate any random numbers. Just in buttonPressed create a constant from shuffled ballArray
let shuffledBallArray = ballArray.shuffled()
now just set images like this:
poolBallView1.image = UIImage(named: shuffledBallArray[0])
poolBallView2.image = UIImage(named: shuffledBallArray[1])
...
So your buttonPressed action should look like this:
#IBAction func buttonPressed(_ sender: UIButton) {
let shuffledBallArray = ballArray.shuffled()
poolBallView1.image = UIImage(named: shuffledBallArray[0])
poolBallView2.image = UIImage(named: shuffledBallArray[1])
poolBallView3.image = UIImage(named: shuffledBallArray[2])
poolBallView4.image = UIImage(named: shuffledBallArray[3])
poolBallView5.image = UIImage(named: shuffledBallArray[4])
}
Creating Unique Random Numbers
Alternatively you can create function which gives you 5 unique random numbers
func generateNumbers(repetitions: Int, maxValue: Int) -> [Int] {
var numbers = [Int]()
for _ in 1...repetitions {
var n: Int
repeat {
n = Int.random(in: 1...maxValue)
} while numbers.contains(n)
numbers.append(n)
}
return numbers
}
and in buttonPressed just create constant for this array of random numbers and set images without saving any image names somewhere in ballArray with hardcoded 50 names
#IBAction func buttonPressed(_ sender: UIButton) {
let randomNumbers = generateNumbers(repetitions: 5, maxValue: 50)
poolBallView1.image = UIImage(named: "poolBall\(randomNumbers[0])")
poolBallView2.image = UIImage(named: "poolBall\(randomNumbers[1])")
poolBallView3.image = UIImage(named: "poolBall\(randomNumbers[2])")
poolBallView4.image = UIImage(named: "poolBall\(randomNumbers[3])")
poolBallView5.image = UIImage(named: "poolBall\(randomNumbers[4])")
}

Create an array. They allow for the storage of multitudes of data and you can reference all of them. Same for images
var randomPoolBallIndices:[Int]!
#IBOutlet weak var poolBallViews: [UIImageView]! //Look up how to make array from IBOutlets
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
randomPoolBallIndices = Array(repeating: 0, count: 5)
}
#IBAction func buttonPressed(_ sender: UIButton) {
for index in randomPoolBallIndices.indices {
let number = Int.random(in: 0 ... 49)
while (randomPoolBallIndices.contains(number)) {
number = Int.random(in: 0 ... 49)
}
randomPoolBallIndices[index] = number
poolBallViews[index] = randomPoolBallIndices[index]
}
}

Generate random number and insert it in Set. When Set count reaches 5, break the loop. That way you can avoid duplication. Then create array of random numbers from set.

Related

UIImageView Array iOS13

I am trying with learning Swift and got stuck on an issue here.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var diceImageView1: UIImageView!
#IBOutlet weak var diceImageView2: UIImageView!
var leftDiceNumber=1
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
diceImageView1.image = UIImage(imageLiteralResourceName: "DiceSix")
// change transparency with diceImageView1.alpha=0.7
}
#IBAction func rollButtonPressed(_ sender: UIButton) {
print("button pressed")
diceImageView1 = [ UIImageView(imageLiteralResourceName: "DiceOne"),UIImageView(imageLiteralResourceName: "DiceTwo"),UIImageView(imageLiteralResourceName: "DiceThree"),UIImageView(imageLiteralResourceName: "DiceFour"),UIImageView(imageLiteralResourceName: "DiceFive"),UIImageView(imageLiteralResourceName: "DiceSix")],[leftDiceNumber]
leftDiceNumber=leftDiceNumber+1
}
}
But all I get is the error messages on the IBAction:
1.Argument passed to call that takes no arguments
2.Cannot assign value of type '[UIImageView]' to type 'UIImageView'
3.Consecutive statements on a line must be separated by ';'
4.Expected expression
What's the difference between UIImageView and UIImage ? When they should be used?
Many Thanks in advance !
You want to change the .image property to change the image.
To "cycle through" the dice, you could do this:
class DiceViewController: UIViewController {
#IBOutlet weak var diceImageView1: UIImageView!
#IBOutlet weak var diceImageView2: UIImageView!
let diceNames: [String] = [
"DiceOne", "DiceTwo", "DiceThree", "DiceFour", "DiceFive", "DiceSix"
]
var leftDiceNumber = 0
override func viewDidLoad() {
super.viewDidLoad()
diceImageView1.image = UIImage(named: diceNames[leftDiceNumber % 6])
}
#IBAction func rollButtonPressed(_ sender: UIButton) {
print("button pressed")
// increment the index
leftDiceNumber += 1
// udpate the image view
diceImageView1.image = UIImage(named: diceNames[leftDiceNumber % 6])
}
}
I'm guessing your goal is to "randomly roll" the dice, so take a look at this slightly different class:
class DiceViewController: UIViewController {
#IBOutlet weak var diceImageView1: UIImageView!
#IBOutlet weak var diceImageView2: UIImageView!
let diceNames: [String] = [
"DiceOne", "DiceTwo", "DiceThree", "DiceFour", "DiceFive", "DiceSix"
]
override func viewDidLoad() {
super.viewDidLoad()
// start with both dice at One
diceImageView1.image = UIImage(named: diceNames[0])
diceImageView2.image = UIImage(named: diceNames[0])
}
#IBAction func rollButtonPressed(_ sender: UIButton) {
print("button pressed")
// arrays are Zero-based, so get a random Int
// from 0 to 5
//let l = Int.random(in: 0...5)
//let r = Int.random(in: 0...5)
//diceImageView1.image = UIImage(named: diceNames[l])
//diceImageView2.image = UIImage(named: diceNames[r])
// more "modern Swifty" method
if let nm = diceNames.randomElement() {
diceImageView1.image = UIImage(named: nm)
}
if let nm = diceNames.randomElement() {
diceImageView2.image = UIImage(named: nm)
}
}
}

Swift UI - Button back on image gallery

How do I make a back button? I get it wrong the way I want to do it. Thank you in advance.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var imageView: UIImageView!
let images: [UIImage] = [#imageLiteral(resourceName: "tub"),#imageLiteral(resourceName: "ball"),#imageLiteral(resourceName: "apple"),#imageLiteral(resourceName: "igloo"),#imageLiteral(resourceName: "frog")]
var i : Int = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func nextButton(_ sender: UIButton) {
i = (i+1)%images.count
imageView.image = images[i]
}
#IBAction func backButton(_ sender: UIButton) {
i = (i-1)%images.count
imageView.image = images[i]
}
the back button gives an error
You have 5 images in your array.
When you tap your Back button, suppose i is currently equal to 0:
(i-1) == -1
-1 % 5 == -1
imageView.image = images[-1] // is invalid... there is no array index of -1
If you want the Back button to "wrap around" from 0 (the first image) to 4 (the last image), you should do:
i -= 1
if i < 0 {
i = images.count - 1
}
imageView.image = images[i]
If you want to stop at the first image:
i = max(i - 1, 0)
imageView.image = images[i]

Cannot assign to value: 'image' is a method [duplicate]

This question already has answers here:
Setting an image for a UIButton in code
(12 answers)
Closed 3 years ago.
I want to change the image displayed by picking a random value from an array of images.
import UIKit
class ViewController: UIViewController {
let imageArray = ["ball1", "ball2", "ball3", "ball4", "ball5"]
var number: Int = 0
#IBOutlet weak var myImage: UIButton!
#IBAction func buttonPressed(_ sender: UIButton) {
number = Int.random(in: 0 ... 4)
myImage.image = UIImage(named: imageArray[number+1])
}
override func viewDidLoad() {
super.viewDidLoad()
myImage.image = UIImage(named: "ball1")
number = Int.random(in: 0 ... 4)
myImage.image = UIImage(named: imageArray[number+1])
}
}
In lines 19, 24, and 26 (whenever I try to change the image) I get the error "Cannot assign to value: 'image is a method". Why is this?
Set image with state property equals to .normal:
import UIKit
class ViewController: UIViewController {
let imageArray = ["ball1", "ball2", "ball3", "ball4", "ball5"]
var number: Int = 0
#IBOutlet weak var myImage: UIButton!
#IBAction func buttonPressed(_ sender: UIButton) {
number = Int.random(in: 0 ... 4)
myImage.setImage(UIImage(named: imageArray[number+1]), for: .normal)
}
override func viewDidLoad() {
super.viewDidLoad()
myImage.setImage(UIImage(named: "ball1"), for: .normal)
number = Int.random(in: 0 ... 4)
myImage.setImage(UIImage(named: imageArray[number+1]), for: .normal)
}
}

How can I perform addition automatically in iOS?

I work on a e-commerce project and now designing basket page. I create 4 steppers for determine to quantity of products. I create labels for show cost of each products and one label for total cost.
#IBOutlet weak var label1: UILabel!
#IBOutlet weak var label2: UILabel!
#IBOutlet weak var label3: UILabel!
#IBOutlet weak var label4: UILabel!
#IBOutlet weak var label5: UILabel!
#IBAction func GmS1(_ sender: GMStepper) {
label1.text = String(sender.value*1.5)
}
#IBAction func GmS2(_ sender: GMStepper) {
label2.text = String(sender.value*0.89)
}
#IBAction func GmS3(_ sender: GMStepper) {
label3.text = String(sender.value*26)
}
#IBAction func GmS4(_ sender: GMStepper) {
label4.text = String(sender.value*4)
}
I don't want to use button but I struggling in addition total cost automatically. My codes are above. Are there anybody know : How can ı addition 4 label in 1 label automatically(without any button).
Label5 for total cost.
You can check photo for general idea.
Make a function sumValues, add all the label's value in it, and assign string of sum to label5.text. This function can be then called from all the IBAction
#IBAction func GmS4(_ sender: GMStepper) {
label4.text = String(sender.value*4)
sumValues()
}
In the function sumValues(),
set label5.text = string of sum of all the labels'.
SideNote - Make sure to initialize value of all labels to 0 in viewDidLoad().
You can try to call this method from every action
func sumAll() {
let sum = [label1,label2,label3,label4].map { Int($0.text ?? "0" ) ?? 0 }.reduce(0,+)
label5.text = "\(sum)"
}
Note: if word variable is part of the label text you may extract number from the text or declare the steppers as outlets and ask them about their current value and at this way use
let sum = [stepper1,stepper2,stepper3,stepper4].map{$0.value}.reduce(0,+)
Continuing from your previous question:
#IBAction func gmstp1(_ sender: GMStepper) {
label1.text = String(sender.value * 1.5)
calculateSum()
}
#IBAction func gmstp2(_ sender: GMStepper) {
label2.text = String(sender.value * 0.89)
calculateSum()
}
#IBAction func gmstp3(_ sender: GMStepper) {
label3.text = String(sender.value * 26.0)
calculateSum()
}
#IBAction func gmstp4(_ sender: GMStepper) {
label4.text = String(sender.value * 4.0)
calculateSum()
}
Where calculateSum is a function defined like so:
func calculateSum() {
if let text1 = label1.text, let value1 = Double(text1),
let text2 = label2.text, let value2 = Double(text2),
let text3 = label3.text, let value3 = Double(text3),
let text4 = label4.text, let value4 = Double(text4) {
let sum = value1 + value2 + value3 + value4
label6.text = String(sum)
}
}
Or if you'd prefer a one-liner:
func calculateSum() {
label5.text = String([label1, label2, label3, label4].reduce(0,{$0 + (Double($1.text ?? "0") ?? 0)}))
}

Swift How To Take Int from two textfield and generate a random number [duplicate]

This question already has answers here:
How to generate a random number in Swift?
(26 answers)
Closed 6 years ago.
I have to text fields on a differnet scene.One text field has a smaller number and another one has a bigger number.I need to take those numbers and generate a random number using the smallest number and the biggest number.Then I needed to make a multiplication problem out of it.Example:User enters in 4 and 8.I need to make two random numbers that is more than 4 and less than 8.Here is my code:
//
// CustomModeWithTimer.swift
// BetaVersion0.1
//
// Created by James Ikeler on 5/26/16.
// Copyright © 2016 James Ikeler. All rights reserved.
//
import UIKit
import Foundation
var CustomNumber1 = UInt32(CustomInputForGame)
var CustomNumber2 = UInt32(CustomInput2ForGame)
var Random = arc4random_uniform(CustomNumber2) + CustomNumber1
var Random2 = arc4random_uniform(CustomNumber2) + CustomNumber1
var UnConvertInt = 0
var scorecustom = 0
var TimerCustom = NSTimer()
var CountDownCustom = 10
var GameOverCustom = UIAlertView()
var AnswerCustom = Int(CustomNumber1 * CustomNumber2)
class CustomModeWithTimer: UIViewController {
#IBOutlet weak var CustomInputForGame3: UITextField!
#IBOutlet weak var QuestionForCustomGame: UILabel!
#IBOutlet weak var ScoreLabelForCustom: UILabel!
#IBOutlet weak var TimerCustomLabel: UILabel!
#IBOutlet weak var RightOrWrongCustom: UILabel!
#IBOutlet weak var CustomImgForGame: UIImageView!
func IfAnswerWrong() {
print("TEST\(AnswerCustom)")
CustomInputForGame3.text = ""
CustomImgForGame.image = UIImage(named: "Label")
CustomImgForGame.hidden = false
RightOrWrongCustom.hidden = false
RightOrWrongCustom.text = "Wrong!"
RightOrWrongCustom.textColor = UIColor(red: 225, green: 0, blue: 0, alpha: 1)
}
func IfAnswerRight() {
CountDownCustom = 10
scorecustom += 1
ScoreLabelForCustom.text = "Score: \(scorecustom)"
Random = arc4random_uniform(CustomNumber2) + CustomNumber1
Random2 = arc4random_uniform(CustomNumber2) + CustomNumber1
QuestionForCustomGame.text = "\(Random) x \(Random2)"
AnswerCustom = Int(Random * Random2)
CustomImgForGame.image = UIImage(named: "Label")
RightOrWrongCustom.hidden = false
CustomImgForGame.hidden = false
RightOrWrongCustom.text = "Right!"
RightOrWrongCustom.textColor = UIColor(red: 0, green: 225, blue: 0, alpha: 1)
CustomInputForGame3.text = ""
}
#IBAction func ConfirmAnswerCustom(sender: AnyObject) {
TimerCustom.invalidate()
TimerCustom = NSTimer.scheduledTimerWithTimeInterval(0.8, target: self,selector: Selector("UpdateClockCustom"), userInfo: nil, repeats: true)
let InputAnswerCustom = Int(CustomInputForGame3.text!)
if InputAnswerCustom == AnswerCustom {
IfAnswerRight();
} else {
IfAnswerWrong();
}
}
func UpdateClockCustom() {
TimerCustomLabel.text = ("Time: \(CountDownCustom--)")
if CountDownCustom == -2 {
TimerCustom.invalidate()
GameOverCustom.title = "Game Over!"
GameOverCustom.message = "Nice job you got a score of \(scorecustom).The answer to the question you missed was \(AnswerCustom)!"
GameOverCustom.addButtonWithTitle("Play Again!")
GameOverCustom.show()
}
}
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.
}
Define a randBetween function:
func randBetween(lower: Int, _ upper: Int) -> Int {
return Int(arc4random_uniform(UInt32(upper - lower - 1))) + lower + 1
}
This returns a random number x where lower < x < upper. It doesn't check that lower + 1 < upper which you can decide how to handle yourself.

Resources