Swift one button 3 messages - ios

I am new to Swift and I am coding on Xcode. I am trying to do like a "Hello, World!" in Swift by having an app that is just one screen, one button, and one display label.
My objective is to have three different messages appear with the click of the button. To clarify, each time I click the button it would cycle through the messages.
I tried solving it with a switch, here is my (unfinished attempt)
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var textBox: UILabel!
var userTapped = false
#IBAction func tappedMe(_ sender: UIButton) {
let me =
if userTapped {
switch me {
case me : textBox.text = "Hello, World!"
case me : textBox.text = "Hello, Human!"
case me : textBox.text = "OK scram."
default : break
}
userTapped = true
}
}
}
I'm not sure what I can make me equal to, or if my solution is even a good one.

class ViewController: UIViewController {
#IBOutlet weak var textBox: UILabel!
let strings = ["Hello, World!", "Hello, Human!", "OK scram."]
var tapCount = 0
#IBAction func tappedMe(_ sender: UIButton) {
textBox.text = strings[tapCount]
tapCount = (tapCount + 1) % strings.count
}
}

You could do something like this it would accomplish your goal if I understand it correctly:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var textBox: UILabel!
// Integer to track number of times button has been tapped
var tapCount = 0
// Max total of text variations, for this case 2 (you have three different values, but always start with zero)
let max = 2
#IBAction func tappedMe(_ sender: UIButton) {
// Try different conditions for value of tapCount
switch tapCount {
case 0:
textBox.text = "Hello, World!"
case 1:
textBox.text = "Hello, Human!"
case 2:
textBox.text = "OK scram."
default : break
}
// If this is the max number of times you want to display changing text, reset tapCount to zero, otherwise increment tapCount.
if tapCount < max {
tapCount += 1
} else {
tapCount = 0
}
}
}

Related

Not Repeating Words in Swift when clicking button - IOS

How can I not repeat the array when I click on the button in swift? I'm trying to generate fruits without them repeating. Can I sort the string that way it runs through all the fruits one by one? It doesn't have to be randomized. I just want each word to show only once when I click the button and show the last array "There aren't any fruit options left"
I tried to randomize the string but that repeats the fruits. I just want it to go one by one. When I press the button on my screen the output on the image label should give me each fruit one at a time.
ie. Button pressed"
Output: "Apple"
button pressed again
Output: "Banana"
and so on until the last string shows "There aren't any fruit options left"
import UIKit
class fruitrandomViewController: UIViewController {
#IBOutlet weak var nextfruitButton: UIButton!
#IBOutlet weak var fruitbox: UILabel!
#IBAction func fruitbutton(_ sender: UIButton) {
let array = ["Apple","Banana","Orange","Pinapple", "Plum", "Pear","T"There aren't any fruit options left",]
let randomFruitgenerator = Int(arc4random_uniform(UInt32(array.count)))
fruitbox.text = array[randomFruitgenerator]
}
}
You need to somehow keep track of the array elements that you have already used. You could do this in a couple of ways:
Keep an index property that tracks the next element of the array
Mutate the array itself as elements are consumed
Either way, you should make the array an instance property, not a local variable in the function itself.
Here is an example of the second approach (I prefer this since I think it makes the code a little simpler, as you don't need to track the next index).
class fruitrandomViewController: UIViewController {
#IBOutlet weak var nextfruitButton: UIButton!
#IBOutlet weak var fruitbox: UILabel!
var fruit = ["Apple","Banana","Orange","Pinapple", "Plum", "Pear",].shuffled()
#IBAction func fruitbutton(_ sender: UIButton) {
if fruit.isEmpty {
fruitbox.text = "There's no more fruit left"
} else {
fruitbox.text = self.fruit[0]
self.fruit.remove(at:0)
}
}
}
For completeness, here is the first approach (with an added "previous fruit" button):
class fruitrandomViewController: UIViewController {
#IBOutlet weak var nextfruitButton: UIButton!
#IBOutlet weak var fruitbox: UILabel!
let fruit = ["Apple","Banana","Orange","Pinapple", "Plum", "Pear",].shuffled()
var nextFruit = 0
#IBAction func fruitbutton(_ sender: UIButton) {
if nextFruit < fruit.count {
fruitbox.text = self.fruit[nextFruit]
nextFruit += 1
} else {
fruitbox.text = "There's no more fruit left"
}
}
#IBAction func previousFruitButton(_ sender: UIButton) {
guard nextFruit > 0 else {
return
}
nextFruit -= 1
fruitbox.text = self.fruit[nextFruit]
}
}
If you don't want the fruit in a random order, just remove the .shuffled()

Hiding UIButton if variable has certain value?

I want to hide a UIButton as long as a certain variable has not reached a certain value.
I tried some setHidden and isHidden setups, but I guess I did it all wrong. I don't exactly know where to put these commands.
I have looked for a solution at almost every webpage but I got no idea what everybody is talking about.
import UIKit
class ViewController: UIViewController {
let startvalue = 1000000
#IBOutlet weak var Counter: UITextField!
#IBAction func Button(_ sender: UIButton) {
if number > 1{
number -= 1
Counter.text = String(number)
} else {
Counter.text = "Hurray"
}
}
#IBOutlet weak var Reset: UIButton!
#IBAction func Reset(_ sender: UIButton) {
if number == 1{
number = startvalue
Counter.text = String (number)
}
}
override func viewDidLoad() {
var number = startvalue {
didSet {
if number < 1 {
Reset.isHidden = false
}
}
}
super.viewDidLoad()
}
}
I don't now what I need to put where to hide Result as long as number is greater than 1.
Handle it in the didSet of the variable.
var number = startValue {
didSet {
if number < 1 {
yourButton.isHidden = false
}
}
}
Now, whenever your number is changed, the didSet block will check if the value is less than 1. If so, it'll unhide the button.
Note: Make sure the button is hidden before the view shows. Also, make sure to hide the button if needed on resetting.
Use lowerCamelCase for variable names like they say in the API design guidelines.

Why wont the points variable display in my label?

I want the Points number to appear on a label which I have called the score. It keeps coming up with errors. I have tried multiple different ways but every time it pulls an error. Can someone resolve this, please?
//VARIABLES
var currentQuestion = 0
var rightAnswerPlacement:UInt32 = 0
var points:UInt32 = 0
//SCORE
#IBOutlet weak var score: UILabel!
//QUESTION
#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
{
score.text = points
}
}
You can't set a UILabel .text property (which is a String) to an Int. You need to make it a String first. Like this:
score.text = "\(points)"
The text property of the UILabel is of type String, so you need to cast points to String before setting it to score.text. Replace:
score.text = points
With:
score.text = "\(points)"
Or
score.text = String(points)
As a side note, in Swift you can write your if statements like this:
if currentQuestion != questions.count {
}

Swift code to make second textfield clear when typing in the second one

I am teaching myself swift for about a week and a half. I am trying to make a converter that goes from inch to centimeters. I have two textfields, one to punch in inches and one for centimeters. When you type one of them in you hit calculate and it gives you either the conversion for inches or centimeters. The problem I am running into is if you fill one in and then you decide you would rather see the other unit of measure, the numbers are still inputed and the button doesn't really work. How can I have the textfield clear if the user decides to use the other field instead?
Also didn't know if it was possible with the code I am uploading, but I would prefer to get rid of the conversion button all together, so when the user types on unit or the other it immediately fills out the label below. is this possible?
here is the code so far.
import UIKit
class ViewController: UIViewController, UITextViewDelegate{
#IBOutlet weak var InchesField: UITextField!
#IBOutlet weak var CentimetersField: UITextField!
#IBOutlet weak var ConversionLabel: UILabel!
//Only let 1 decimal point
let numberFormatter: NumberFormatter = {
let nf = NumberFormatter()
nf.numberStyle = .decimal
nf.minimumFractionDigits = 0
nf.maximumFractionDigits = 1
return nf
}()
#IBAction func ConversionButton1(_ sender: AnyObject) {
if InchesField.text == "" || CentimetersField.text == "" {
//either inchfield or centimetersfield text is empty
ConversionLabel.text = String("Please enter a number")
}
if let text = InchesField.text, !text.isEmpty
{
//do something if it's not empty
let inch = Double(InchesField.text!)
let inCmConvertor = inch! * 2.54
ConversionLabel.text = String("\(inCmConvertor) Centimters")
} else
if let text = CentimetersField.text, !text.isEmpty
{
let centimeter = Double(CentimetersField.text!)
let cmInConvertor = centimeter! / 2.54
ConversionLabel.text = String("\(cmInConvertor) Inches")
}
}
}
Heres a screenshot
What you want to do is create an IBAction for each Text Field with the Editing Changed event in the IBAction creation window.
I tested the code below and it worked:
#IBOutlet weak var InchesField: UITextField!
#IBOutlet weak var CentimetersField: UITextField!
#IBAction func InchesFieldChanged(_ sender: Any) {
CentimetersField.text = ""
}
#IBAction func CentimetersFieldChanged(_ sender: Any) {
InchesField.text = ""
}
Don't copy and paste the code, just create the IBActions manually, it will be much simpler.
Good luck with your journey into Swift programming and iOS development.

Xcode - Label won't clear when button is pressed

So I'm trying to create a simple function in my app in which a button adds 1 integer to the label when it's pressed and the other one clears it.
Here is the code:
class ViewController: UIViewController {
var number = 0
#IBOutlet weak var tapCount: UILabel!
#IBAction func plusTapped(sender: AnyObject) {
number = number + 1
tapCount.text = String(number)
}
#IBAction func minusTapped(sender: AnyObject) {
var totalNumber = number - number
tapCount.text = String(totalNumber)
}
However the label does clear when the minus button is tapped but when the plus button is tapped after, it adds up from the previous number before the minus button was pressed.
How do I fix this in a way so that it actually clears the label?
#IBAction func minusTapped(sender: AnyObject) {
number = 0 // add this line to reset the counter, the real number
tapCount.text = String(number)
}
Try
#IBAction func minusTapped(sender: AnyObject) {
number = 0
tapCount.text = String(0)
}
I think it's because when you're handling tap on minus you are altering local variable and not changing number itself. You should change "number" too. Se my comments in your's code
class ViewController: UIViewController {
var number = 0
#IBOutlet weak var tapCount: UILabel!
#IBAction func plusTapped(sender: AnyObject) {
number = number + 1
tapCount.text = String(number)
}
#IBAction func minusTapped(sender: AnyObject) {
//here totalNumber is changed but number is still the same
var totalNumber = number - number
tapCount.text = String(totalNumber)
}

Resources