UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

class function to disable button

Forums > SwiftUI

I've done a lot of programming in the past, I'm just getting started with Swift and SwiftUI, so apologies if this is a silly question.

My first, playful, app is a BMI calculator. I have a class BMI, which conforms to ObservableObject and has properties bmi, weight and height. It has a function, calc() to calculate the BMI. bmi is @Published. The instance of BMI in ContentView is declared as @ObservedObject. When the "calculate bmi" button is pressed, the calc() method is called, it assigns a value to the bmi property and that is shown in its view. So far, so good.

The "calculate" button is modified by .disabled(bmi.shouldDisable()). The shouldDisable() function returns true if values have been entered into the weight and height fields.

My problem is that the shouldDisable() function isn't getting called when I enter stuff into the weight/height TextFields.

I'm obviously missing something here, which is probably simple: how do I get a View to be bound to a function, in the same way in which it can be bound to a variable?

Thanks in advance.

Jeremy

2      

Add a computed property that check to see if a value has been entered in TextField

var validEntry: Bool {
  if Double(weight) = nil || Double(height) = nil {
    return true
  }
  return false
}

then on Button (in SwiftUI)

.disabled(validEntry)

2      

Thanks. I had tried that and failed. However, I've changed the class to a struct and it works well now.

Jeremy

2      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.