1. 程式人生 > >RxSwift:RxSwift初體驗

RxSwift:RxSwift初體驗

將TextField裡面輸入的內容和label繫結起來

檔名 ViewController.swift

//
//  ViewController.swift
//  RxSwiftTest
//
//  Created by travey on 2018/11/5.
//  Copyright © 2018年 ZhouShijie. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa
import SnapKit

    class ViewController: UIViewController {
        var textField: UITextField!
        var label: UILabel!
        let disposeBag = DisposeBag()
        
        override func viewDidLoad() {
            
            textField = UITextField(frame: CGRect(x: 0, y: 0, width: 300, height: 50))
            textField.layer.borderWidth = 1
            view.addSubview(textField)
            
            label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
            label.textAlignment = .center
            view.addSubview(label)
            
            textField.snp.makeConstraints { (make) in
                make.width.equalTo(200)
                make.height.equalTo(50)
                make.center.equalToSuperview()
                
            }
            label.snp.makeConstraints { (make) in
                make.width.equalTo(200)
                make.height.equalTo(50)
                make.centerX.equalTo(textField.snp.centerX)
                make.top.equalTo(textField.snp.bottom).offset(20)
            }
            
            //將textField輸入的文字繫結到label上
            textField.rx.text
                .bind(to: label.rx.text)
                .disposed(by: disposeBag)
        }
    }