LoginSignup
6
8

More than 5 years have passed since last update.

テキストの長さによって背景を動的に可変(見せかけを)するUITextView

Last updated at Posted at 2017-02-27

はじめに

こんにちは。
チャットアプリやメモアプリなどで利用するような
背景の長さが可変のUITextViewの実装に少し悩んだので書いてみました。
至らぬ点など多々あると思いますが、コメントなど頂けたら幸いです。

サンプル

sample.gif

Storyboardの準備

実はUITextViewの高さが伸び縮みしているわけではなく
後ろに配置した背景色の付いたUIViewが動的に可変するようにしています。

UIView(背景)の制約

UIViewConstraint.png

UITextViewの制約

UITextViewConstraint.png

また、背景のUIViewのHeightのConstraintUITextViewのbottomのConstraint
以下のようにIBOutlet接続します。
(画像ではUITextViewのbottomConstraintを繋げています。同じようにUIViewのHeightConstraintも接続してください。)

screen3.png

中身に合わせて背景UIViewが伸びすぎないように調節

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

UITextView_Height.png

なので、伸びすぎた際はWindowのサイズ(見た目のサイズ)に合わせるように調節します。

if textView.frame.height <= textViewBackgroundView.frame.height {
    textViewBackgroundHeightConstraint.constant = textView.frame.size.height
}

サンプルコード

MainViewController.swift
import UIKit

class MainViewController: UIViewController {

    @IBOutlet weak var textView: UITextView!
    @IBOutlet weak var textViewBackgroundView: UIView!

    @IBOutlet weak var textViewBottomConstraint: NSLayoutConstraint!
    @IBOutlet weak var textViewBackgroundHeightConstraint: NSLayoutConstraint!

    override func viewDidLoad() {
        super.viewDidLoad()
        textView.delegate = self
        NotificationCenter.default.addObserver(self,
        selector: #selector(MainViewController.showKeyBoard(_:)),
        name: NSNotification.Name.UIKeyboardWillShow,
        object: nil)
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        textView.becomeFirstResponder()
        textView.tintColor = UIColor.black
    }

    deinit {
        NotificationCenter.default.removeObserver(self)
    }

    //キーボードが表示された時の処理
    func showKeyBoard(_ notification: Notification) {
        if let userInfo = (notification as NSNotification).userInfo {
            if let keyboard = userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue{
                textViewBottomConstraint.constant = keyboard.cgRectValue.size.height
            }
        }
    }
}

extension MainViewController: UITextViewDelegate {
    //textに変更があった際に呼び出される
    func textViewDidChange(_ textView:UITextView) {
        if textView.frame.height <= textViewBackgroundView.frame.height {
            textViewBackgroundHeightConstraint.constant = textView.frame.size.height
        }else {
            textViewBackgroundHeightConstraint.constant = textView.sizeThatFits(textView.frame.size).height
        }
    }
}

参考にさせていただいた記事

見て頂いてありがとうございます。

6
8
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
6
8