I want Subtract process with Button action but my code does not work.
I made the Number. This number is Main number for user's game money. I set the '1,000'. This I set the name of this "playerMoney"
After that I made the #IBAction Button for Discount the '500' number from 'playerMoney'. This button's action means buy Game item things.
I set the name of '500' number is "chocolatePrice" and Button's name is "buyChocolateButton"
I also print playerMoney on the UILable.
I set that label name is "printPlayerMoney"
I'm using the code below.
import UIKit
class ViewController: UIViewController {
var playerMoney = 1000
var chocolatePrice = 500
#IBOutlet weak var printPlayerMoney: UILabel!
#IBAction func buyChocolateButton(sender: AnyObject) {
playerMoney = playerMoney - chocolatePrice
}
override func viewDidLoad() {
super.viewDidLoad()
printPlayerMoney.text = "\(playerMoney)"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
You need to put the printPlayerMoney.text = "\(playerMoney)" inside the button function. That way, overtime you press the button, it does the calculation and then updates the label. See the updated code below:
class ViewController: UIViewController {
var playerMoney: Int = 1000
var chocolatePrice: Int = 500
#IBOutlet weak var printPlayerMoney: UILabel!
#IBAction func buyChocolateButton(sender: AnyObject) {
playerMoney = playerMoney - chocolatePrice
printPlayerMoney.text = "\(playerMoney)"
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
printPlayerMoney.text = "\(playerMoney)"
doesn't watch the value of playerMoney
After changing the value of playerMoney, we have to set the text of the UILabel again if we're expecting a visual change
Related
I want to create a simple BMI calculator using height and weight and I am having trouble converting my UITextField strings to integers for the calculation.
Here's my working code:
import UIKit
class BMICalculator: UIViewController {
//MARK: Properties
#IBOutlet weak var weightField: UITextField!
#IBOutlet weak var heightField: UITextField!
#IBOutlet weak var solutionTextField: UILabel!
#IBAction func calcButton(_ sender: AnyObject) {
let weightInt = Int(weightField)
let heightInt = Int(heightField)
solutionTextField.text = weightInt/(heightInt*heightInt)
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Anyone have any ideas? I tried searching for the solution but couldn't find anything specific to this issue.
Use this:
guard let text1 = weightField.text else {
return
}
guard let text2 = heightField.text else {
return
}
guard let weightInt = Int(text1) else {
return
}
guard let heightInt = Int(text2) else {
return
}
solutionTextField.text = weightInt /(heightInt*heightInt)
//Change your name for this outlet 'solutionTextField' to 'solutionLabel' since it is a UILabel not UITextField
The TextField only accepts a String, it wont take an Int.
Change this:
solutionTextField.text = weightInt/(heightInt*heightInt)
To this:
solutionTextField.text = String(weightInt/(heightInt*heightInt))
I don't think your code is working. To get the values out of your UITextFields and convert them to Ints, you'll need to pull them out of the '.text properties. Then, when you calculate the result, you'll need to convert it back to a string and set solutionTextField?.text equal to that result.
class BMICalculator: UIViewController {
//MARK: Properties
#IBOutlet weak var weightField: UITextField!
#IBOutlet weak var heightField: UITextField!
#IBOutlet weak var solutionTextField: UILabel!
#IBAction func calcButton(_ sender: AnyObject) {
let weightInt = Int((weightField?.text!)!)
let heightInt = Int((heightField?.text!)!)
let solution = weightInt!/(heightInt!*heightInt!)
solutionTextField?.text = "\(solution)"
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Keep in mind that this code is very dangerous because you're not safely unwrapping optionals, but that's a different thread.
Hope this helps.
Good morning!
I have an "unable to load" problem in my iOS widget. I've read a lot of about the "unable to load" message but nothing fixed my problem. I'm not sure but I think my problem is to refresh the widget after changing my content.
My widget has one button and one label. If the user press the button the text from the label will changed - in this moment the widget shows "unable to load". Just a milisecond after pressing the button.
import UIKit
import NotificationCenter
class TodayViewController: UIViewController, NCWidgetProviding {
#IBOutlet var segment_att: UISegmentedControl!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)) {
completionHandler(NCUpdateResult.NewData)
}
func widgetMarginInsetsForProposedMarginInsets(defaultMarginInsets: UIEdgeInsets) -> UIEdgeInsets {
return UIEdgeInsetsZero
}
#IBAction func button_ae(sender: AnyObject) {
let tableviewclass = TodayTableViewController()
tableviewclass.newData()
}
}
Important is that the label is shown in a TableViewCell of a TableViewController. So the TableViewController is embeded in the ViewController within a Container... The listener from the button call the method newdata() of the file of the TableViewController.
import UIKit
import NotificationCenter
class TodayTableViewController: UITableViewController, NCWidgetProviding {
#IBOutlet var table: UITableView!
#IBOutlet var label1: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
init()
}
func init() {
let meldung: String = "test"
label1.text = meldung
}
func newData() {
let meldung: String = "new test"
label1.text = meldung
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
The code is really simple and basic - so I'm wondering about the problem in this simple mechanism. I hope you can help me!
Thanks at all!
Your code assumes that label1 has been set when newData() is called, even immediately after the constructor is called.
Try using this optional chaining syntax instead, which will quietly fail if the property is nil:
import UIKit
import NotificationCenter
class TodayTableViewController: UITableViewController, NCWidgetProviding {
#IBOutlet var table: UITableView!
#IBOutlet var label1: UILabel!
var meldung: String = "test" // <-- meldung is property
override func viewDidLoad() {
super.viewDidLoad()
init()
}
func init() {
label1?.text = melding // <-- optional chaining
}
func newData() {
melding = "new test" // <-- set the class property
label1?.text = meldung // <-- optional chaining
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
and instead of calling newData(), you might instead just set the meldung property, e.g.:
tableviewclass.meldung = "new test"
as your viewDidLoad() will take care of setting the UILabel text from the property
So, straight in to it. I wish to change the value of a label depending on the position of the UISlider. If the slider is in position 1, and untouched, the label should show "Regular", at value 2 it should show "Soy" and value 3, "Almond".
In case you hadn't guessed already, it is to make a milk choice.
Ideally I wish to use a switch/case. The slider has a minimum value of 1 which refers to regular milk. The aim for the app is to use the cloud down the line to save order information, so I am open as to which would be the best solution complying to this future requirement.
Thanks!
Currently....
#IBOutlet weak var sugarValue: UILabel!
#IBOutlet weak var sugarStepper: UIStepper!
#IBOutlet weak var milkChoice: UILabel!
#IBOutlet weak var milkChoiceSlider: UISlider!
#IBAction func sugarChange(sender: UIStepper) {
sugarValue.text = Double(sugarStepper.value).description
}
#IBAction func milkChoiceChange(sender: UISlider) {
milkChoice.text = String(milkChoiceSlider.value)
}
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.
}
I'm aware that the current set up would not show the text in the label, I was trying to just get it to show the 1, 2, 3 values first but to no avail.
Here is a code snippet... As you see, you can use an array of values, in this case you don't need "case" :)
import UIKit
class ViewController: UIViewController {
#IBOutlet var milkChoiceLabel: UILabel!
#IBOutlet var milkChoiceSlider: UISlider!
#IBOutlet var sugarValue: UILabel!
var labelValues: [String] = ["Regular", "Soy", "Almond"]
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 sliderValueChanged(sender: UISlider) {
sender.value = roundf(sender.value)
let value = Int(sender.value)
sugarValue.text = value.description
// switch (sender.value) {
// case 1:
// milkChoiceLabel.text = labelValues[0]
// break
// case 2:
// milkChoiceLabel.text = labelValues[1]
// break
// case 3:
// milkChoiceLabel.text = labelValues[2]
// break
// default:
// break
// }
// or better ...
milkChoiceLabel.text = labelValues[value - 1];
}
}
The real problem here is that you're misusing a UISlider as a tri-state switch. A slider is continuous; it's not a switch. If you wanted a tri-state switch, you should use a tri-state switch, namely a UISegmentedControl.
I'm currently developing a counter app which every time you press a button it will count up. I have already done this and works 100%, what I'm trying to do is make a another button and when you press it, it shows the current number on the console but it only prints out 0 because that's the default variable I assigned the value to.
My whole class:
var counterNumber = 0
#IBOutlet weak var counterLabel: UILabel!
func initCount(){
counterNumber = 0
}
func numberUp(){
self.counterNumber++;
counterLabel.text = "\(self.counterNumber)"
}
#IBAction func CountUp(sender: UIButton) {
numberUp()
}
#IBAction func RestartButton(sender: UIButton) {
initCount()
}
#IBAction func printButton(sender: UIButton) {
self.numberUp();
print(self.counterNumber)
}
override func viewDidLoad() {
super.viewDidLoad()
initCount()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
Just call method numberUp in printButton: action.
var counterNumber = 0//this is a variable of class
#IBOutlet weak var counterLabel: UILabel!
#IBAction func printButton(sender: UIButton) {
self.numberUp();
print(self.counterNumber)
}
func numberUp(){
self.counterNumber++;
counterLabel.text = "\(self.counterNumber)"
}
Use 'self' keyword to call instance variables.
class ViewController: UIViewController {
// Properties
var counterNumber:Int = 0 // Make this variable Global to Class
// IBOutlets Properties
#IBOutlet weak var counterLabel: UILabel!
#IBAction func printButton(sender: UIButton) {
self.numberUp()
self.counterLabel.text = "\(self.counterNumber)"
print("\n You Pressed ==> \(sender.title) button \(self.counterNumber) times")
}
func numberUp() {
self.counterNumber += 1
self.counterLabel.text = "\(counterNumber)"
}
}
When I create an IBaction for a button I can easily get it to perform an action for example:
#IBAction func click(sender: AnyObject) {
label6.hidden = false}
How do I get it to execute a totally different task when it is clicked for a second or third time etc?
Thanks
EDIT: When I try this I get an error "Viewcontroller.type does not have a member named "label1", this also is stated for "label2" Any ideas why as I have already added the label in as an outlet. Do I need to declare it somewhere else to get it to work? Thanks
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
label1.text = ""
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBOutlet weak var label1: UILabel!
#IBOutlet weak var label2: UILabel!
class MyButtonClass
{
var clickCounter: Int = 0
#IBAction func click(sender: AnyObject)
{
clickCounter += 1
if (clickCounter == 1)
{label1.text = "text1"}
else if (clickCounter == 2)
{label2.text = "text1"
clickCounter = 0}
}
}
}
Replace your code with the following:
class ViewController: UIViewController
{
override func viewDidLoad()
{
super.viewDidLoad()
label1.text = ""
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBOutlet weak var label1: UILabel!
#IBOutlet weak var label2: UILabel!
var clickCounter: Int = 0
#IBAction func click(sender: AnyObject)
{
clickCounter += 1
if (clickCounter == 1)
{
label1.text = "text1"
}
else if (clickCounter == 2)
{
label2.text = "text1"
clickCounter = 0
}
}
}
You can have a counter and depending on its value fire another method from the one called on click
Create a property that counts the tap count
Increment the tap count on each click
Implement a switch on the tap count to perform different actions (IBAction acts as a dispatcher)