I'm creating a simple app using Swift that tells you if the number you are entering is a prime number or not. I know the logic is correct, but when I run the app and enter a number and press the button my label is not updating like it should. Can someone help me?
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var number: UITextField!
#IBOutlet weak var results: UILabel!
#IBAction func buttonPressed(sender: AnyObject) {
var numberInt = number.text.toInt()
if numberInt != nil {
var unwrappedNumber = numberInt!
var isPrime = true
if unwrappedNumber == 1 {
isPrime = false
}
if unwrappedNumber != 2 && unwrappedNumber != 1 {
for var i = 2; i < unwrappedNumber; i++ {
if unwrappedNumber % i == 0 {
isPrime = false
}
}
}
if isPrime == true{
results.text = "\(unwrappedNumber)Is Prime"
}else {
results.text = "\(unwrappedNumber)Is not Prime"
}
}else {
results.text = "Enter a number"
}
}
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.
}
}
The problem in your project is you are performing a wrong action at wrong place like in your StoryBoard you right Click on TextField you find that you connected Editing Did End is connected with #IBAction func buttonPressed(sender: AnyObject) this action. because of this your action is not working.
Now the solution for your problem is remove your action connection from that textField by Clicking that cross button and it will look like :
after that connect ** buttonPressed** action with Run Test Button like this:
HERE I updated your code.
I recommended you to watch some tutorial on UI so you can batter understands how this all things works.
Related
I am learning swift3 programming but after executing my calculator app its crashing in between. Please check the below code.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var aLabel: UILabel!
#IBOutlet weak var commmon_button: UIButton!
var a: Int?
var b: Int?
var sum: Int?
var val = ""
#IBOutlet weak var text_feild: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func clik_button(_ sender: UIButton) {
val=String(sender.tag)
text_feild.text = text_feild.text! + val
}
#IBAction func fn_addition(_ sender: UIButton) {
a = Int(text_feild.text!)
}
#IBAction func fn_answer(_ sender: UIButton) {
b = Int(text_feild.text!)
sum = a! + b!
a = 0
b = 0
text_feild.text = nil
text_feild.text = String(sum!)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
During run time i am getting crash at fn_addition by saying Thread 1 breakpoint 2.1
Initiliaze your variables as below
var a = 0
var b = 0
var sum = 0
Replace your methods with below methods.
#IBAction func clik_button(_ sender: UIButton) {
guard let value = String(sender.tag), let text = text_feild.text
else {
return
}
text_feild.text = text + value
}
#IBAction func fn_addition(_ sender: UIButton) {
guard let aValue = Int(text_feild.text)
else{
return
}
a = aValue
}
#IBAction func fn_answer(_ sender: UIButton) {
guard let bValue = Int(text_feild.text)
else{return}
b = bValue
sum = a + b
a = 0
b = 0
text_feild.text = ""
text_feild.text = String(sum)
}
Suggestion: You are using same text field for taking a , b values and for showing sum result. It is better to use two different text fields for taking a and b values separately. Take a label to show sum value.
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
I'm learning swift by building a basic counting app (based on this tutorial https://www.youtube.com/watch?v=3blma4PCRak) and I'm trying to have a function that counts on increments of 3 based on the state of a switch.
It seems a lot of the answers I find in tutorials online and from SO are from many years ago and a lot of the syntax is deprecated, including:
• instead of oddSwitch.On now it is oddSwitch.isOn
• Stating colors changed from UIColor.redColor to just UIColor.red
And so on...below is my code thus far:
//
// ViewController.swift
// TestApp
//
// Created by kawnah on 2/8/17.
// Copyright © 2017 kawnah. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
#IBOutlet var outputLabel: UILabel? = UILabel();
var currentCount = 0;
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.
}
#IBAction func addOneBUtton(_ sender: UIButton) {
currentCount = currentCount + 1
if currentCount <= 1 {
outputLabel?.text = "\(currentCount) click"
} else {
outputLabel?.text = "\(currentCount) clicks"
}
outputLabel?.textColor = UIColor.red
}
#IBOutlet var oddSwitch: UISwitch!
#IBAction func oddToggle(_ sender: UISwitch) {
if oddSwitch!.isOn {
currentCount = currentCount + 3
}
}
}
I'm confused as to the relationship between the #IBOutlet and my function that states to count in increments of three. I've tried including weak storage as well but it's to my understanding that is the default for #IBOutlet. Currently when I toggle the switch on, the counter still increments by 1.
My error log simply shows compression errors for PNGs for my splash screen, nothing with the code. What exactly is happening?
Change your addOneBUtton code to match this.
#IBAction func addOneBUtton(_ sender: UIButton) {
if oddSwitch!.isOn {
currentCount = currentCount + 3
} else {
currentCount = currentCount + 1
}
if currentCount <= 1 {
outputLabel?.text = "\(currentCount) click"
} else {
outputLabel?.text = "\(currentCount) clicks"
}
outputLabel?.textColor = UIColor.red
}
And you can remove this section.
#IBAction func oddToggle(_ sender: UISwitch) {
if oddSwitch!.isOn {
currentCount = currentCount + 3
}
}
So the complete code should look something like this.
import UIKit
class testViewController: UIViewController {
//MARK: IBOutlets
#IBOutlet var outputLabel: UILabel? = UILabel();
#IBOutlet var oddSwitch: UISwitch!
//MARK: Vars
var currentCount = 0;
//MARK: Lifecyle
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
//MARK: IBActions
#IBAction func addOneBUtton(_ sender: UIButton) {
if oddSwitch!.isOn {
currentCount = currentCount + 3
} else {
currentCount = currentCount + 1
}
if currentCount <= 1 {
outputLabel?.text = "\(currentCount) click"
} else {
outputLabel?.text = "\(currentCount) clicks"
}
outputLabel?.textColor = UIColor.red
}
}
Note: This was my twist on keeping the code clean with IBOutlets all in one spots and using //MARK: to the sections of code quicker to jump to.
I'm new to Swift, and I'm trying to make a little app that, given two values (a,b) returns a random number between the two numbers (a < randomnumber < b)
The user has to write the values of a and b in two different text fields and then just press a button and that's it
The problem is:
I told the NSLog to display the two values just before generating the random number because I noticed something wasn't working as it was supposed to, and the result is that apparently the second value I insert, whether it is a or b, for some (unknown) reason, equals 0 ! For example, if I write in the a-textfield the value 10 and then I insert the value 40 in the b-textfield, the NSLog displays a = 10, b = 0. If I insert the b value before, the NSLog displays b = 40, a = 0.
These are the lines of code :
#IBAction func TextAAction(sender: AnyObject) {
a = UInt32(TextA.text!)!
}
#IBAction func TextBAction(sender: AnyObject) {
b = UInt32(TextB.text!)!
}
#IBAction func randomInBetweenAction(sender: AnyObject) {
NSLog("a=%ld, b=%ld", a, b)
randomInBetween()
unHide()
Label.text = "\(randomNumberInBetween)"
}
as you can see the value a is equal to the value that is inserted in the TextA field and the value b is equal to the value that is inserted in the TextB field
the randomInBetween() is the function that generates a random number between a and b, and it does work.. the problem is that one of the values (the second one I insert) is always 0 for some reason, even if I set it to a different number!
Any ideas on why this happens and how to work it out?
#ReinerMelian this is the full code
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var Label: UILabel!
#IBOutlet weak var Button: UIButton!
#IBOutlet weak var InvariableLabel: UILabel!
#IBOutlet weak var TextA: UITextField!
#IBOutlet weak var TextB: UITextField!
#IBOutlet weak var AndLabel: UILabel!
#IBOutlet weak var Button2: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
Hide()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
var randomNumber = Int()
func randomNUMBER() -> Int {
randomNumber = Int(arc4random())
return randomNumber
}
func Hide() {
Label.hidden = true
}
func unHide() {
Label.hidden = false
}
var a = UInt32()
var b = UInt32()
var randomNumberInBetween = Int()
func randomInBetween() -> Int {
if b>a {
randomNumberInBetween = Int(arc4random_uniform(b - a) + a)
return randomNumberInBetween
} else {
randomNumberInBetween = Int(arc4random_uniform(a - b) + a)
return randomNumberInBetween
}
}
#IBAction func ButtonAction(sender: AnyObject) {
randomNUMBER()
unHide()
Label.text = "\(randomNumber)"
NSLog("\(randomNumber)")
}
#IBAction func TextAAction(sender: AnyObject) {
a = UInt32(TextA.text!)!
}
#IBAction func TextBAction(sender: AnyObject) {
b = UInt32(TextB.text!)!
}
#IBAction func randomInBetweenAction(sender: AnyObject) {
NSLog("a=%ld, b=%ld", a, b)
randomInBetween()
NSLog("\(randomInBetween)")
unHide()
Label.text = "\(randomNumberInBetween)"
NSLog("\(randomInBetween)")
}
}
(PS: as you can see, there is also a function that generates a random number without any sort of constraints, but that part works just fine.. the problem is with the other part of the code, the one that returns a random number between two given values (a,b) )
make sure, your outlets (TextA, TextB) and your IBAction (randomInBetweenAction) are wired up correctly, remove
#IBAction func TextAAction(sender: AnyObject) {
a = UInt32(TextA.text!)!
}
and
#IBAction func TextBAction(sender: AnyObject) {
b = UInt32(TextB.text!)!
}
and try this function on button tap:
#IBAction func randomInBetweenAction(sender: AnyObject) {
a = UInt32(TextA.text!)!
b = UInt32(TextB.text!)!
NSLog("a=%ld, b=%ld", a, b)
randomInBetween()
NSLog("\(randomInBetween)")
unHide()
Label.text = "\(randomNumberInBetween)"
NSLog("\(randomInBetween)")
}
I am experimenting with buttons, and I have run into what is probably a simple problem. I have two buttons and two labels.
The labels generate random string values of either "A" or "B". I want the correct label to disappear if the appropriate button is selected.
I have come up with the following code, but I have run into a problem. If the letters are the same, both labels will be hidden when the corresponding button is tapped.
I understand why this is happening, I think. It's because my code is executed when buttonA is tapped once(I haven't started on button B yet, so it doesn't do anything.)
So my question is how do I require 2 taps? In other words, if label_1 and label_2 are both displayed as String "A", how would i require the user to tap buttonA twice? If more code is needed, let me know in the comments.
#IBOutlet weak var label_1: UILabel!
#IBOutlet weak var label_2: UILabel!
#IBOutlet weak var label_3: UILabel!
#IBOutlet weak var label_4: UILabel!
#IBOutlet weak var label_5: UILabel!
var visibleLetters = ["A", "B", "Z", "X"]
var text = "", text2 = "", text3 = "", text4 = "", text5 = ""
let aButton = "A", bButton = "B", zButton = "Z", xButton = "X"
var x = 0
override func viewDidLoad() {
super.viewDidLoad()
createRandomLetter(text, aSecondLetter: text2, aThirdLetter: text3, aFourthLetter: text4, aFifthLetter: text5)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func buttonA(sender: UIButton) {
if aButton == label_1.text {
label_1.hidden = true
label_1.tag += 1
}
else {
//play animation
print("play animation")
}
}
#IBAction func buttonB(sender: UIButton) {
if bButton == label_1.text {
label_1.hidden = true
}
}
#IBAction func buttonX(sender: UIButton) {
if xButton == label_1.text {
label_1.hidden = true
}
}
#IBAction func buttonZ(sender: UIButton) {
if zButton == label_1.text {
label_1.hidden = true
}
}
func createRandomLetter(individualLetter: String, aSecondLetter: String, aThirdLetter: String, aFourthLetter: String, aFifthLetter: String) {
let individuaLetter = visibleLetters[Int(arc4random_uniform(UInt32(visibleLetters.count)))],
aSecondLetter = visibleLetters[Int(arc4random_uniform(UInt32(visibleLetters.count)))],
aThirdLetter = visibleLetters[Int(arc4random_uniform(UInt32(visibleLetters.count)))],
aFourthLetter = visibleLetters[Int(arc4random_uniform(UInt32(visibleLetters.count)))],
aFifthLetter = visibleLetters[Int(arc4random_uniform(UInt32(visibleLetters.count)))]
label_1.text = individuaLetter
label_2.text = aSecondLetter
label_3.text = aThirdLetter
label_4.text = aFourthLetter
label_5.text = aFifthLetter
}
func isCorrect() {
if aButton == label_1.text {
label_1.hidden = true
label_1.tag += 1
}
else if label_1.tag == 1 && aButton == label_2.text {
}
else {
//play animation
print("play animation")
}
}
}
OK trying to figure it out what you are trying to do let's do an example. So you have 4 labels, and 2 Buttons (A,B), the labels have random generated values of A,B when you click a button you need to check if that button has the same text of the label then if it is correct we do the same with label2 if it's not correct we keep trying.
A logical way to do this can be to associate tags to your labels (that i think you are alredy doing it) and have a temporal variable to keep track of the current label for example
var temporal:String!
var current_tag:Int = 1
override func viewDidLoad() {
super.viewDidLoad()
createRandomLetter(text, aSecondLetter: text2,
aThirdLetter: text3, aFourthLetter: text4, aFifthLetter: text5)
temporal = label1.text
}
#IBAction func buttonZ(sender: UIButton) {
//Answer is correct
if zButton == temporal {
current_tag++
IsCorrect(current_tag)
}
}
func Iscorrect(tag:Int)
{
if(label2.tag == tag)
{
temporal = label2.text
}
else if(label3.tag == tag)
{
temporal = label2.text
}
else if(label4.tag == tag)
{
temporal = label2.text
}
}
Somethign like that should work, I didn't try it as I'm answering from my Ipad and I do not have access to my laptop but something like that should totally work, any doubt I can help you XD