Skip to content

Instantly share code, notes, and snippets.

@YusukeHosonuma
Created June 5, 2016 12:44
Show Gist options
  • Save YusukeHosonuma/7c1b5b72dff2f85ce1eefc95d23b1fbe to your computer and use it in GitHub Desktop.
Save YusukeHosonuma/7c1b5b72dff2f85ce1eefc95d23b1fbe to your computer and use it in GitHub Desktop.
RxSwift: Two UITextView text count.
import UIKit
import RxSwift
import RxCocoa
class ViewController: UIViewController {
@IBOutlet weak var textView: UITextView!
@IBOutlet weak var countLabel: UILabel!
@IBOutlet weak var textView2: UITextView!
@IBOutlet weak var countLabel2: UILabel!
let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
// textView
textViewCountObservable(textView)
.bindTo(countLabel.rx_text)
.addDisposableTo(disposeBag)
// textView2
textViewCountObservable(textView2)
.bindTo(countLabel2.rx_text)
.addDisposableTo(disposeBag)
}
/**
指定されたTextViewの初期表示・内容の変更時に、入力されている文字数のテキストが流れるObservable.
ex) "hello" -> "count: 5"
- parameter textView: textView
- returns: Observable
*/
func textViewCountObservable(textView: UITextView) -> Observable<String> {
return NSNotificationCenter.defaultCenter()
.rx_notification(UITextViewTextDidChangeNotification, object: textView)
.startWith(NSNotification(name: "start", object: nil))
.map{ _ -> String in
let count: Int = textView.text?.characters.count ?? 0
return "count: \(count)"
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment