RxSwift简单使用2-UI

1、UITextField限制输入字数

private func setupRAC() {
        
        rightTextField.rx.text.orEmpty.subscribe(onNext: { [weak self] (text) in
            guard let `self` = self else { return }
            
            var string = text
            
            // 获取非选中状态文字范围
            let selectedRange = self.rightTextField.markedTextRange
            
            // 没有非选中文字,截取多出的文字
            if selectedRange == nil {
                
                if string.count > 10 {
                    string = (string as NSString).substring(to: 10)
                    self.rightTextField.text = string
                }
                
                if let model = self.addressModel {
                    model.textFieldValue = string
                    debugPrint("textFieldValue = \(string)")
                }
            }
            
        }).disposed(by: rx.disposeBag)
        
        
        Observable.of(multiLineTextField.rx.text).merge().subscribe(onNext: { [weak self] in
            guard let `self` = self else { return }
            
            if var string = $0 {
                
                if string.count > 200 {
                    //通过字符串截取实现限制200字符长度
                    string = (string as NSString).substring(to: 200)
                    self.multiLineTextField.text = string
                }
                
                if let model = self.addressModel {
                    model.textFieldValue = string
                }
                debugPrint("multiLineTextField.frame = \(self.multiLineTextField.frame)")
            }
            
        }).disposed(by: rx.disposeBag)
    }

你可能感兴趣的:(RxSwift简单使用2-UI)