Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxSwift: enable/disable button based on textfields are not empty

Tags:

swift

rx-swift

I have to enable a button based on the characters count on two textfields using RxSwift

@IBOutlet weak var userTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var buttonToEnableDisable: UIButton!

var enabledObservable = combineLatest(userTextField.rx_text, passwordTextField.rx_text) 
{ (user,password) in
   self.loginButton.enabled = a.characters.count > 0 && b.characters.count > 0
}

Finally i acomplish by doing this, but i'm not sure if its the best way:

    _ = combineLatest(emailTextField.rx_text, passwordTextField.rx_text) { (a: String, b:String) in
        self.loginButton.enabled = (a.characters.count > 0 && b.characters.count > 0)
    }.subscribeNext { (result) -> Void in
    }

Edit final version:

    _ = combineLatest(emailTextField.rx_text, passwordTextField.rx_text) { (a: String, b:String) in
        return (a.characters.count > 0 && b.characters.count > 0)
        }.subscribeNext { enabled in
            self.loginButton.alpha = enabled ? 1 : 0.5
            self.loginButton.enabled = enabled
        }
        .addDisposableTo(disposeBag)
like image 564
Godfather Avatar asked Dec 03 '15 08:12

Godfather


1 Answers

If I understood you correctly, You probably want something like this

  let loginValidation = loginTextFiled
     .rx_text
     .map({!$0.isEmpty})
     .shareReplay(1)

  let userNameValidation = passwordTextField
     .rx_text
     .map({!$0.isEmpty})
     .shareReplay(1)

  let enableButton = combineLatest(loginValidation, userNameValidation) { (login, name) in
     return login && name
  }

  enableButton
     .bindTo(loginButton.rx_enabled)
     .addDisposableTo(disposeBag)

For more details I suggest you to look at RxExamples

There you can find a lot of answers to the common problems. Have fun =)

like image 191
Serg Dort Avatar answered Sep 28 '22 05:09

Serg Dort