2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

RxSwiftを使って動的なTextViewを作る

Last updated at Posted at 2019-11-05

実装するもの:TextViewを動的に可変するやつ

rxswift.gif

↑これをRxswiftで実装していきます。
(ネットにあまり情報がなかったので、初学者のために掲載します.)

早速はじめましょう。

①配置とオートレイアウト

以下のようになっています。

TextViewを可変にするにあたって重要な点は、Heghtを変動させることです。
今回の仕組みはこれが全てです。
しっかりオートレイアウトをしましょう。

スクリーンショット 2019-11-05 21.45.18.png

②コーディング

全体は以下のようになっています。

HogeViewController.swift
class HogeViewController: UIViewController {
    
    @IBOutlet weak var textView: UITextView!
    
    @IBOutlet weak var textViewHeightConstraint: NSLayoutConstraint!
    private let disposeBag = DisposeBag()

    override func viewDidLoad() {
        super.viewDidLoad()
        setup()
    }
    
    private func setup(){
        
        textView.rx.text
            .asDriver()
                .drive(onNext: { [ weak self ] _ in
                    let size:CGSize = self!.textView.sizeThatFits(self!.textView.frame.size)
                    self!.textView.frame.size.height = size.height
                    self!.textViewHeightConstraint.constant = size.height
                    self!.view.setNeedsLayout()
                    
                    }, onCompleted: {
                        print("完了")
                }) {
                    self.disposeBag
            }
    }

}

一文ずつ見てもらえれば、だいたいわかるので特に解説はしないのですが、
一つだけ注意点として

@IBOutlet weak var textViewHeightConstraint: NSLayoutConstraint!

これは、TextViewのオートレイアウトで固定したHeghtだってことです。

終わりに

RxSwiftでUIを制御するのはとても便利なのですが、やはり初学者にとっては難しい場面もあります。
API周辺を交えたものをプロジェクトに組み込めるところまで、頑張りましょう、、、、💦

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?