enable NSButton if NSTextfield is not empty - swift

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
}
}
}

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 ?.

Can't get result from two UITextField on 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!)!)
}

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: ""))!)"
}

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!

Disable button in cocoa application OS X

I would like to have the submit button enabled once some fields on a form have been validated. Currently the preview function works great, preview button provides the validation I need. Working on Xcode 7 and swift 2. I would really appreciated if someone can point me in the right direction. Below is the code I currently have:
import Cocoa
#NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
var projectFlag = false
var descriptionFlag = false
var releaseFlag = false
// Fields
#IBOutlet weak var projectNumberTextField:NSTextField!
#IBOutlet weak var projectDescriptionTextField:NSTextField!
#IBOutlet weak var releaseFolderNameTextField:NSTextField!
#IBOutlet weak var passwordTextField:NSTextField!
// Labels for preview
#IBOutlet weak var label1: NSTextField!
#IBOutlet weak var label2: NSTextField!
#IBOutlet weak var label3: NSTextField!
#IBOutlet weak var label4: NSTextField!
#IBOutlet weak var label5: NSTextField!
// Quit Button :: Quits the application
#IBAction func quitButton(sender: AnyObject) {
NSApplication.sharedApplication().terminate(self)
}
// Preview button behavior
#IBAction func previewButton(sender: AnyObject) {
// Project Number ::
let project = projectNumberTextField.stringValue
label1.stringValue = "\(project)"
if (label1.stringValue == "00-0000") {
label1.stringValue = "Project Number is not valid"
label1.textColor = NSColor.redColor()
projectFlag = false
} else {
label1.textColor = NSColor.blackColor()
projectFlag = true
}
// Project Description :: Name, 2016
let description = projectDescriptionTextField.stringValue
label2.stringValue = "\(description)"
if (label2.stringValue == "Name, 2016") {
label2.stringValue = "Enter a valid project description"
label2.textColor = NSColor.redColor()
descriptionFlag = false
} else {
label2.textColor = NSColor.blackColor()
descriptionFlag = true
}
// Folder Release Name :: RELEASE_NAME
let release = releaseFolderNameTextField.stringValue
label3.stringValue = "\(release)"
if (label3.stringValue == "RELEASE_NAME") {
label3.stringValue = "Enter a valid folder release name"
label3.textColor = NSColor.redColor()
releaseFlag = false
} else {
label3.textColor = NSColor.blackColor()
releaseFlag = true
}
// Password :: If needed
let password = passwordTextField.stringValue
label4.stringValue = "\(password)"
// Preview :: Code format for txt file
let preview = "\(project)|"+"\(description)|"+"\(release)|"+"\(password)/"
label5.stringValue = "\(preview)"
}
// Submit button behavior
#IBAction func submitButton(Sender: AnyObject) {
}
func applicationDidFinishLaunching(aNotification: NSNotification) {
// Insert code here to initialize your application
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
}