Can't get result from two UITextField on swift - swift

var widthValue : Int = 0
var heightValue : Int = 0
var result : Int = 0
#IBOutlet weak var widthText: UITextField!
#IBOutlet weak var heightText: UITextField!
#IBOutlet weak var resultText: UILabel!
#IBAction func calculate(_ sender: Any) {
widthText.text = "\(widthValue)"
heightText.text = "\(heightValue)"
resultText.text = "\(widthValue + heightValue)"
}
Two UITextFields to hold an Int then resultText displays in a UILabel named resultText.

I figure you're trying to add numbers from two text fields.
For that,
Change following
resultText.text = "\(widthValue + heightValue)"
To
let additionResult = widthText.text + heightText.text
resultText.text = additionResult

You should be getting the values of widthText and heightText. Something like this would work
#IBAction func calculate(_ sender: UIView) {
resultText.text = String(Int(heightText.text!)! + Int(widthText.text!)!)
}

Related

I am trying to add a UILabel exactly like I already have but keep getting this error

I am trying to add a label to my calculator where it shows the tip amount but I keep getting
Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value
I just want it to display the tip amount as well. I copied it exact for the other UILabel.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var PriceTxt: UITextField!
#IBOutlet weak var Tip: UITextField!
#IBOutlet weak var totalFinal: UILabel!
#IBOutlet weak var TipAmount: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
totalFinal.text = ""
TipAmount.text = ""
}
#IBAction func Calcualte(_ sender: Any) {
if PriceTxt.text! == "" || Tip.text! == ""
{
totalFinal.text = "Input the Numbers"
TipAmount.text = ""
}
else {
let price = Double(PriceTxt.text!)!
let tipPer = Double(Tip.text!)!
let TipMult = price * (tipPer/100)
let TipFinal = Double((round(100*TipMult)/100) + price)
totalFinal.text = "$\(TipFinal)"
TipAmount.text = "$\(TipMult)"
}
}
}
It will show you the problem in your code.. please always try to avoid force cast
class ViewController: UIViewController {
#IBOutlet weak var PriceTxt: UITextField!
#IBOutlet weak var Tip: UITextField!
#IBOutlet weak var totalFinal: UILabel!
#IBOutlet weak var TipAmount: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
totalFinal.text = ""
TipAmount.text = ""
}
#IBAction func Calcualte(_ sender: Any) {
if let getPrice = PriceTxt.text , let getTip = Tip.text
{
if getPrice.isEmpty || getTip.isEmpty {
totalFinal.text = "Input the Numbers"
TipAmount.text = ""
}
else {
let price = Double(getPrice)!
let tipPer = Double(getTip)!
let TipMult = price * (tipPer/100)
let TipFinal = Double((round(100*TipMult)/100) + price)
totalFinal.text = "$\(TipFinal)"
TipAmount.text = "$\(TipMult)"
}
} else {
print("either PriceTxt or Tip is nil")
}
}
}
Try using ? instead of !
! force unwraps and gives you a fatal error if there is no value (nil). ? only unwraps if a value is present.
Also, why unwrap the text here at all?
Use
PriceTxt.text == "" || Tip.text == "" without the ! or ?.

How to Collect the numbers in Lebel text

I want Collect the price to print Total amount as Label
#IBOutlet weak var typlabale: UILabel!
#IBOutlet weak var fruitLabel: UILabel!
#IBOutlet weak var typPrice: UILabel!
#IBOutlet weak var fruitPrice: UILabel!
#IBOutlet weak var totaleValue: UILabel!
var CupValue: Int = 8
var ConeValue: Int = 20
var StrawberryValue : Int = 20
var RaspberryValue : Int = 20
var BananaValue : Int = 10
// Mark : - Typ selec
#IBAction func typesegm(_ sender: Any) {
switch typesegm.selectedSegmentIndex
{
case 0:
typlabale.text = "Cup"
typPrice.text = "$\(CupValue)"
case 1:
typlabale.text = "Cone"
typPrice.text = "$\(ConeValue)"
default:
break;
}
}
// Fruit
#IBAction func fruitSegm(_ sender: Any) {
switch fruit.selectedSegmentIndex
{
case 0:
fruitLabel.text = "Strawberry"
fruitPrice.text = "$\(StrawberryValue)"
case 1:
fruitLabel.text = "Raspberry"
fruitPrice.text = "$\(RaspberryValue)"
case 2:
fruitLabel.text = "Banana"
fruitPrice.text = "$\(BananaValue)"
default:
break;
}
}
Add this line
totaleValue.text = "$\(Int(typPrice.text!.replacingOccurrences(of: "$", with: ""))! + Int(fruitPrice.text!.replacingOccurrences(of: "$", with: ""))!)"
in end of typesegm and fruitSegm method like this.
#IBAction func typesegm(_ sender: Any) {
switch typesegm.selectedSegmentIndex
{ ... }
totaleValue.text = "$\(Int(typPrice.text!.replacingOccurrences(of: "$", with: ""))! + Int(fruitPrice.text!.replacingOccurrences(of: "$", with: ""))!)"
}
#IBAction func fruitSegm(_ sender: Any) {
switch fruit.selectedSegmentIndex
{ ... }
totaleValue.text = "$\(Int(typPrice.text!.replacingOccurrences(of: "$", with: ""))! + Int(fruitPrice.text!.replacingOccurrences(of: "$", with: ""))!)"
}

enable NSButton if NSTextfield is not empty

I am creating a OSX app and would like to enable a button when all textfield are filled. But do not have much experience with osx app as there seem to be some difference from ios.
This is what I have tried.
override func viewDidLoad() {
super.viewDidLoad()
btnCalculate.enabled = false
}
override func controlTextDidChange(obj: NSNotification) {
if panelsWideTextField.stringValue.isEmpty {
btnCalculate.enabled = false
} else {
btnCalculate.enabled = true
}
}
Hope someone has a good tip for me :-)
EDIT:
Complete code.
import Cocoa
//import AppKit
class ViewController: NSViewController, NSTextFieldDelegate {
#IBOutlet weak var panelHightTextField: NSTextField!
#IBOutlet weak var panelWidthTextField: NSTextField!
#IBOutlet weak var panelPitchTextField: NSTextField!
#IBOutlet weak var panelsHighTextField: NSTextField!
#IBOutlet weak var panelsWideTextField: NSTextField!
#IBOutlet weak var resWidthLabel: NSTextField!
#IBOutlet weak var resHightLabel: NSTextField!
#IBOutlet weak var lblScreenWidth: NSTextField!
#IBOutlet weak var lblScreenHight: NSTextField!
#IBOutlet weak var lblScreenArea: NSTextField!
#IBOutlet weak var btnCalculate: NSButton!
#IBOutlet weak var lblAmountPanels: NSTextField!
var panelHight = ""
var panelWidth = ""
var panelPitch = ""
var panelsHigh = ""
var panelsWidth = ""
var resWidth : Float = 0
var resHigh : Float = 0
var screenHight : Float = 0
var screenWidth : Float = 0
var screenArea : Float = 0
var ammountPanels : Float = 0
override func viewDidLoad() {
super.viewDidLoad()
btnCalculate.enabled = false
}
override func controlTextDidChange(obj: NSNotification) {
if panelsWideTextField.stringValue.isEmpty {
btnCalculate.enabled = true
} else {
btnCalculate.enabled = false
}
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
#IBAction func calculateResButton(sender: AnyObject) {
takeUserData()
calculatehight()
calculatewidth()
calculateArea()
calculateAmountPanels()
}
func takeUserData(){
panelHight = panelHightTextField.stringValue
panelWidth = panelWidthTextField.stringValue
panelPitch = panelPitchTextField.stringValue
panelsHigh = panelsHighTextField.stringValue
panelsWidth = panelsWideTextField.stringValue
}
// Calculating resolution and physical hight
func calculatehight(){
let fpanelHight = Float(panelHight)
let fpanelPitch = Float(panelPitch)
let fpanelsHigh = Float(panelsHigh)
resHigh = fpanelHight! * fpanelsHigh! / fpanelPitch!
screenHight = fpanelHight! * fpanelsHigh! / 1_000
printText()
}
// Calculating resolution and physical width
func calculatewidth(){
let fpanelWidth = Float(panelWidth)
let fpanelPitch = Float(panelPitch)
let fpanelsWidth = Float(panelsWidth)
resWidth = fpanelWidth!*fpanelsWidth!/fpanelPitch!
screenWidth = fpanelWidth!*fpanelsWidth! / 1_000
printText()
}
// Calculating sqm of LED screen
func calculateArea(){
let fpanelHight = Float(panelHight)
let fpanelsHigh = Float(panelsHigh)
let fpanelWidth = Float(panelWidth)
let fpanelsWidth = Float(panelsWidth)
screenArea = (fpanelHight! * fpanelsHigh!) * (fpanelWidth! * fpanelsWidth!) / 1_000_000
printText()
}
// Calculating the amount of panels used.
func calculateAmountPanels(){
let fpanelsHigh = Float(panelsHigh)
let fpanelsWidth = Float(panelsWidth)
ammountPanels = (fpanelsWidth! * fpanelsHigh!)
printText()
}
// Outputting text to labels with correct format.
func printText(){
let formatResHigh = String(format: "%0.0f", resHigh)
let formatResWidth = String(format: "%0.0f", resWidth)
let formatScreenHight = String(format: "%0.2f", screenHight)
let formatScreenWidth = String(format: "%0.2f", screenWidth)
let formatScreenArea = String(format: "%0.0f", screenArea)
let formatAmmountPanels = String(format: "%0.0f", ammountPanels)
resHightLabel.stringValue = "\(formatResHigh)px"
resWidthLabel.stringValue = "\(formatResWidth)px"
lblScreenHight.stringValue = "\(formatScreenHight)m"
lblScreenWidth.stringValue = "\(formatScreenWidth)m"
lblScreenArea.stringValue = "\(formatScreenArea) sqm"
lblAmountPanels.stringValue = "\(formatAmmountPanels)"
}
}
I had the same problem but I found simple solution: checkbox can enable and disable NSButton.
import Cocoa
class ViewController: NSViewController {
#IBOutlet weak var btnCalculate: NSButton!
#IBOutlet weak var checkBox: NSButton!
override func viewDidLoad() {
super.viewDidLoad()
btnCalculate.enabled = false
checkBox.state = 0
}
#IBAction func checkAgree(sender: NSButton) {
if btnCalculate.stringValue.characters.count > 0 && checkBox.state == 1 {
btnCalculate.enabled = true
} else {
btnCalculate.enabled = false
}
}
}

RxSwift 'bindTo(aNSButton.rx_enabled)' failed

here is my code:
let aDisposeBag = DisposeBag()
class LoginController: NSViewController {
#IBOutlet weak var accountField: NSTextField!
#IBOutlet weak var passwdField: NSSecureTextField!
#IBOutlet weak var loginBtn: NSButton!
override func viewDidLoad() {
super.viewDidLoad()
let accAvailable = accountField.rx_text.map({(aa)-> Bool in
print("aa")
return aa.characters.count > 0
})
let passAvailable = passwdField.rx_text.map({(aa)-> Bool in
print("bb")
return aa.characters.count > 0
})
let allAvailable = Observable.combineLatest(accAvailable, passAvailable){$0 && $1}
allAvailable.bindTo(loginBtn.rx_enabled).addDisposableTo(aDisposeBag)
}
}
When I input contents into accountField,nothing prints in the console.
But if I replace allAvailable.bindTo(loginBtn.rx_enabled).addDisposableTo(aDisposeBag) into
allAvailable.subscribeNext { (available) in
print(available)
}.addDisposableTo(aDisposeBag)
Then I can see aa or bb is printed in the console.
Anyone can tell what's wrong with my code,thanks a lot!

Displaying an Array of type Double on UILabel in Xcode

I am trying to make a basic shopping cart app where you can add an item to your cart, store the cost of the item in an array and then have the array displayed when you click "Receipt". However, every time I click "Receipt" on my app, the simulator crashes and displays
"Thread1: EXC_BAD_INSTRUCTION (code=EXC_1386_INVOP, subcode=0x0)
beside my line of code that reads "allItems += item". If anyone has any ideas as to how I can my array of numbers displayed in a UILabel using a for in loop, please let me know. I will post source code below. Thanks in advance
class ViewController: UIViewController {
var priceOfApple = 1.75
var cart = [Double]()
var total = 0.00
#IBOutlet weak var appName: UILabel!
#IBOutlet weak var Balance: UILabel!
#IBOutlet weak var Instructions: UILabel!
#IBOutlet weak var redApple: UIButton!
#IBOutlet weak var appleInfo: UILabel!
#IBOutlet weak var addToCart: UIButton!
#IBOutlet weak var itemsPurchased: UILabel!
#IBAction func selectedApple(sender: AnyObject) {
Instructions.hidden = true
appleInfo.hidden = false
addToCart.hidden = false
}
#IBAction func purchaseApple(sender: AnyObject) {
cart.append(priceOfApple)
total += priceOfApple
Balance.text = "Balance : \(total)"
Instructions.hidden = false
appleInfo.hidden = true
addToCart.hidden = true
}
#IBAction func viewReceipt(sender: AnyObject) {
redApple.hidden = true
Instructions.hidden = true
itemsPurchased.hidden = false
for item in cart {
var allItems = Double(itemsPurchased.text!)!
allItems += item
allItems = Double(itemsPurchased.text!)!
}
}
}
If I understand correctly, this is what you should do:
First, create a variable outside the for-loop,
then inside the loop that variable will start storing every value in the array separated by " ". Once It is done, you can display its value in the Label.
var itemsInCart = ""
for items in cart{
itemsInCart += String(items) + " "
}
itemsPurchased.text = itemsInCart
I hope it helps!!!
A cleaner and safer way to do it:
let result = cart.flatMap { Double(itemsPurchased.text ?? String()) }.reduce(0: combine: +)
Doing that, you shouldn't get EXC_BAD_INSTRUCTION anymore, but you should still check if is the text convertible to a Double.