代码之家  ›  专栏  ›  技术社区  ›  Asi Givati

RXSwift-根据其他元素使一个UI元素隐藏/不隐藏

  •  0
  • Asi Givati  · 技术社区  · 6 年前

    我正在使用 RxSwift RxCocoa 在我的项目中。

    我有一些 UITextField 名为“lastnametf”,有一个 UILabel 姓名“lastnametitle”。

    我想知道有没有办法 isHidden LastnameTitle的值始终等于 伊希丁 lastname的值tf使用 RXSwift公司 .

    3 回复  |  直到 6 年前
        2
  •  1
  •   Popmedic    6 年前

    Here is an example

    class ViewController: UIViewController {
        private var lastNameTextFieldHiddenContext = 0
        private var lastNameObservingView:UIView? = nil
        @IBOutlet weak var lastNameLabel: UILabel!
        @IBOutlet weak var lastNameTextField: UITextField!
    
        override func viewDidLoad() {
            super.viewDidLoad()
            // add the observer
            lastNameTextField.addObserver(
                self,
                forKeyPath: "hidden",
                options: [.new],
                context: &self.lastNameTextFieldHiddenContext
            )
        }
    
        /// function will be called whenever an added observer is triggered
        override func observeValue(
            forKeyPath keyPath: String?,
            of object: Any?,
            change: [NSKeyValueChangeKey : Any]?,
            context: UnsafeMutableRawPointer?
        ) {
            // make sure it is our text field isHidden observer
            if context == &self.lastNameTextFieldHiddenContext {
                // get the new value that was set
                if let newValue = change?[NSKeyValueChangeKey.newKey] as? Bool {
                    // do what needs to be done when the observer is triggered
                    self.lastNameLabel.isHidden = newValue
                }
            }
        }
    
        deinit {
            // remove the observer
            if let view = self.lastNameObservingView {
                view.removeObserver(self, forKeyPath: "hidden")
                self.lastNameObservingView = nil
            }
        }
    
        @IBAction func showHideButtonAction(_ sender: Any) {
            self.lastNameTextField.isHidden = !self.lastNameTextField.isHidden
        }
    }
    
        3
  •  0
  •   juliancadi    6 年前

    // Controls are visible by default (isHidden = false)
    let isControlHidden = BehaviorRelay<Bool>(value: false)
    
    override func viewDidLoad() {
      super.viewDidLoad()
    
      let isHiddenDriver = self.isControlHidden.asDriver()
    
      isHiddenDriver
        .drive(self.lastNameTitle.rx.isHidden)
        .disposed(by: disposeBag)
    
      isHiddenDriver
        .drive(self.lastNameTF.rx.isHidden)
        .disposed(by: disposeBag)
    }
    

    @IBAction func hide(_ sender: Any) {
      self.isControlHidden.accept(true)
    }
    
    @IBAction func show(_ sender: Any) {
      self.isControlHidden.accept(false)
    }