美文网首页Swift开发
UITextField字数限制(RxSwift版)

UITextField字数限制(RxSwift版)

作者: CN_HarrySun | 来源:发表于2018-10-10 17:12 被阅读29次
  baseView.phoneField.rx.controlEvent([.editingChanged])
            .asObservable()
            .subscribe(onNext: { [weak self] _ in
                guard let `self` = self else { return }
                
                // 获取非选中状态文字范围
                let selectedRange = self.baseView.phoneField.markedTextRange
                // 没有非选中文字,截取多出的文字
                if selectedRange == nil {
                    let text = self.baseView.phoneField.text ?? ""
                    if text.count > 12 {
                        let index = text.index(text.startIndex, offsetBy: 13)
                        self.baseView.phoneField.text = String(text[..<index])
                    }
                }
                
            })
            .disposed(by: disposeBag)

相关文章

网友评论

    本文标题:UITextField字数限制(RxSwift版)

    本文链接:https://www.haomeiwen.com/subject/kjcmaftx.html