LoginSignup
3

More than 5 years have passed since last update.

【Swift】text の変更後に UITextView を一番下までスクロールするコード

Last updated at Posted at 2016-12-28

text を変更する前に isScrollEnabled を false にするのがコツです。

コードによるテキスト変更では、デリゲードや通知は使えないようです。
ソフトキーボードによる変更では使えます。

Swift
class ViewController: UIViewController {
    @IBOutlet weak var textView: UITextView!

    ---- 省略 ----

    // textView に変更を加えるメソッド 適宜必要な処理に読み替えてください
    func addText(_ text: String) {
        textView.isScrollEnabled = false
        textView.text = textView.text + text
        scrollToButtom()
    }

    func scrollToBottom() {
        textView.selectedRange = NSRange(location: textView.text.characters.count, length: 0)
        textView.isScrollEnabled = true

        let scrollY = textView.contentSize.height - textView.bounds.height
        let scrollPoint = CGPoint(x: 0, y: scrollY > 0 ? scrollY : 0)
        textView.setContentOffset(scrollPoint, animated: true)
    }
}

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
3