I am trying to program a simple app in Xcode using Swift.
I have two labels which contain INT values which are incremented up/down by the user using Steppers as per below:
class ViewController: UIViewController {
#IBOutlet weak var valueLabel: UILabel!
#IBOutlet weak var stepper: UIStepper!
#IBAction func stepperValueChanged(sender: UIStepper) {
valueLabel.text = Int(sender.value).description
}
#IBOutlet weak var valueLabel2: UILabel!
#IBOutlet weak var stepper2: UIStepper!
#IBAction func stepperValueChanged2(sender: UIStepper) {
valueLabel2.text = Int(sender.value).description
}
I want to then have another Label (label3) which takes the INTs from label1 & label2 and divides them.
So for example if the user has Label1 as '5' and label2 as '10' I want label3 to display '0.5'.
Is there an easy way that I can do this?
As I'm sure you can tell, I'm really new to iOS development so any help or advice would be greatly appreciated!
Cheers!
Although this is a simple program you should still use best practice and adopt a model-view-controller design. Your model (data) should be separate from view (in essence the way the data is displayed). In a more 'serious' application the model would typically be a separate class, but in this case you can use local properties.
Storing data in Int properties also means you won't have to convert back from strings when you want to perform calculations.
class ViewController: UIViewController {
#IBOutlet weak var valueLabel: UILabel!
#IBOutlet weak var stepper: UIStepper!
#IBOutlet weak var valueLabel2: UILabel!
#IBOutlet weak var stepper2: UIStepper!
#IBOutlet weak var valueLabel3: UILabel!
var value1=0;
var value2=0;
#IBAction func stepperValueChanged(sender: UIStepper) {
self.value1=Int(sender.value);
self.valueLabel1.text="\(self.value1)";
self.updateResult();
}
#IBAction func stepperValueChanged2(sender: UIStepper) {
self.value2=Int(sender.value);
self.valueLabel1.text="\(self.value1)";
self.updateResult();
}
func updateResult {
if (self.value2 != 0) {
var result=Float(self.value1)/Float(self.value2)
self.valueLabel3.text="\(result)"
} else {
self.valueLabel3.text="Can't divide by 0"
}
}
}
Related
[![enter image description here][2]][2]i want to programm an App with two ViewControllers
The first one performs a segue to the second VC.
The Second VC has a Scrollview with different Views.
I did everything with Autolayout not with code
When i run the Application i get always the error "whose view is not in the window hierarchy!" and can't scroll to the bottom. I tried to find some solutions but nothing helped.
Hope someone can help me with the problem.
my first VC runs a normal performSegue("identifier",sender )
my code for the second VC is
import UIKit
class FragenViewController: UIViewController {
var fragen = [Question]()
var highscore = 0
var questionNumber = 0
#IBOutlet weak var titleLabel: UILabel!
#IBOutlet weak var questionLabel: UILabel!
#IBOutlet weak var answerButton1: UIButton!
#IBOutlet weak var answerButton2: UIButton!
#IBOutlet weak var answerButton3: UIButton!
#IBOutlet weak var answerButton4: UIButton!
#IBOutlet weak var forwardButton: UIButton!
#IBOutlet weak var scoreLabel: UILabel!
#IBOutlet weak var currentQuestionLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func answerButton_Tapped(_ sender: UIButton) {
}
}
the rest is with Main Storyboard Drag and drop
The Code from the first VC is
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var titleLabel: UILabel!
#IBOutlet weak var highscoreLabel: UILabel!
#IBOutlet weak var startButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Setup Layout
startButton.backgroundColor = UIColor.systemFill
startButton.layer.cornerRadius = 20
startButton.titleLabel?.font = UIFont(name: "Arial", size: 20)
startButton.layer.borderWidth = 2
startButton.tintColor = UIColor.systemBlue
highscoreLabel.font = UIFont(name: "Arial", size: 18)
}
#IBAction func start_Button(_ sender: Any) {
performSegue(withIdentifier: "startGame", sender: sender)
}
}
I am a beginner working on an app that will function like a golf scorecard. My first issue has come while attempting to accept user input in a (prototype) series of 9 textFields so the user can type in their scores, and then a textView at the end that is not editable that will show the total for the 9 holes. I am trying to get this to be a running total that updates constantly.
I tried passing the inputs from each textField into an array, and returning the sum of the array to a the textView, but still had issues with the data type from the textField being a string, where as I will only be dealing with integers.
My clunky first pass is as follows -
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var holeOneScore: UITextField!
#IBOutlet weak var holeTwoScore: UITextField!
#IBOutlet weak var holeThreeScore: UITextField!
#IBOutlet weak var holeFourScore: UITextField!
#IBOutlet weak var holeFiveScore: UITextField!
#IBOutlet weak var holeSixScore: UITextField!
#IBOutlet weak var holeSevenScore: UITextField!
#IBOutlet weak var holeEightScore: UITextField!
#IBOutlet weak var holeNineScore: UITextField!
#IBOutlet weak var totalForFrontNine: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
//MARK: Calculate Scores
#IBAction func calculate(_ sender: Any) {
let hole1:Int = Int(holeOneScore.text!)!
let hole2:Int = Int(holeTwoScore.text!)!
let hole3:Int = Int(holeThreeScore.text!)!
let hole4:Int = Int(holeFourScore.text!)!
let hole5:Int = Int(holeFiveScore.text!)!
let hole6:Int = Int(holeSixScore.text!)!
let hole7:Int = Int(holeSevenScore.text!)!
let hole8:Int = Int(holeEightScore.text!)!
let hole9:Int = Int(holeNineScore.text!)!
let totalArray = [hole1, hole2, hole3, hole4, hole5, hole6, hole7, hole8, hole9]
let totalScore = totalArray.reduce(0, +)
totalForFrontNine.text = String(totalScore)
print(totalForFrontNine!)
}
It worked, but barely. Any thoughts to modify this or a complete refresh is fine! I am not tied to anything as i am using this project to just teach me the basics.
Thanks in advance, cheers - glassGarrett
Like #jawadali mentioned, use IBOutletCollection. Here is a tutorial about how to use it.
As for the other issue,
...the data type from the textField being a string, where as I will only be dealing with integers.
A quick solution is to set the keyboardType of your textfield to UIKeyboardTypeNumberPad, or .numberPad in Swift.
textField.keyboardType = .numberPad
Or in storyboard,
I'm currently teaching myself in Swift and Xcode.
At the moment I'm trying to get some user input over a UITextField and I want to store them in an Array. The array should go through a for-loop to show the stored data in a UITextView.
At the start I tried it with one user input. It worked.
#IBOutlet weak var InputPlayerName: UITextField!
#IBOutlet weak var SubmitPlayer: UIButton!
#IBOutlet weak var ShowPlayerName: UITextView!
#IBOutlet weak var ShowSize: UITextView!
var players = [String]()
#IBAction func SubmittedPlayer(_ sender: Any) {
players.append(ShowPlayerName.text);
let playerssize = players.count;
ShowSize.text = "\(playerssize)";
for player in players {
if(playerssize == 1) {
ShowPlayerName.text = "Player: \n \(player)";
} else {
ShowPlayerName.text += "\(player)";
}
}
I don't get any errors, it just doesn't show me the results. But the arraysize grows if I press the button.
How can I show the Data line per line in the View?
Sorry if this particular problem has been asked about, I followed the answers on other threads but none of them seemed to work, but I just started learning Swift so all of this is pretty new to me.
So, I have a text field in two View Controllers and I want the third View Control to display a result based on the input from the other two controllers when I press a button.
I followed this tutorial and placed the text fields, label and button like I said before.
I placed my code (which you can see below) inside ViewControl.swift.
The problem is that when I attempt to run it I get a "Thread 1 :EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)" error in the last two lines.
class ViewController: UIViewController {
var a: String = ""
var b: String = ""
#IBOutlet weak var aTextField: UITextField!
#IBOutlet weak var bTextField: UITextField!
#IBOutlet weak var calculateButton: UIButton!
#IBOutlet weak var resultLabel: UILabel!
#IBAction func calculateButtonPressed(_ sender: UIButton) {
let a = aTextField.text!;
let b = bTextField.text!;
I think that the error is from the data not passing between the views (because before I had everything in the same view and it worked fine), but since I only have one ViewController.swift file I couldn't figure out how to use a Segue.
Do not declare same variables multiple times. Remove let before a & b . You have already declared a & b globally and then tried to redeclare it inside IBAction
class ViewController: UIViewController {
var a: String = ""
var b: String = ""
#IBOutlet weak var aTextField: UITextField!
#IBOutlet weak var bTextField: UITextField!
#IBOutlet weak var calculateButton: UIButton!
#IBOutlet weak var resultLabel: UILabel!
#IBAction func calculateButtonPressed(_ sender: UIButton) {
a = aTextField.text!;
b = bTextField.text!;
Make sure your control outlets are setted properly.
In your two variables a & b are re-declared.Just update your code like below
#IBAction func calculateButtonPressed(_ sender: UIButton) {
self.a = aTextField.text!
self.b = bTextField.text!
}
This is my first question (and program in Xcode to be honest) so apologies if I break any formatting rules, etc!
I am having an issue when creating an area calculator (to be used at a later date in a quote calculator) and having looked at every SIGABRT thread I could find, but I have been unable to resolve it.
import UIKit
class ViewController: UIViewController{
#IBOutlet weak var forename: UITextField!
#IBOutlet weak var surname: UITextField!
#IBOutlet weak var email: UITextField!
#IBOutlet weak var widthInput: UITextField!
#IBOutlet weak var lengthInput: UITextField!
#IBOutlet weak var areaOutput: UILabel!
#IBOutlet weak var perimeterOutput: UILabel!
#IBOutlet weak var results: UILabel!
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 calculate(sender: AnyObject) {
let width = NSString(string: widthInput.text).doubleValue
let length = NSString(string: lengthInput.text).doubleValue
// The calculation used to work out the area of a room
var area = width * length
areaOutput.text = "\(area)"
// The calculation used to work out the perimeter of a room
var perimeter = 2 * (length + width)
perimeterOutput.text = "\(perimeter)"
}
Any help would be appreciated.
Thanks,
Marc