LoginSignup
3

More than 5 years have passed since last update.

UITextViewでPlaceholderを実装する(Swift4対応版)

Last updated at Posted at 2018-06-27

UITextFieldにはplaceholderがありますが、UITextViewにはありません。
今回は、UITextViewでもplaceholderを使えるように、新しいクラスを作って見ました。

実装方法

UITextViewを継承した新しいClass(ファイル)を作成
UITextViewにCustomClassとしてPlaceHolderTextViewを指定
ソースコードでplaceholderの文字と文字色を指定

PlaceHolderTextView.swift

import UIKit

public class PlaceHolderTextView: UITextView {

    lazy var placeHolderLabel:UILabel = UILabel()
    var placeHolderColor:UIColor = UIColor.lightGray
    var placeHolder:NSString = ""

    required public init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!
    }

    deinit {
        NotificationCenter.default.removeObserver(self)
    }

    override public func awakeFromNib() {
        super.awakeFromNib()

        NotificationCenter.default.addObserver(self, selector: #selector(textChanged), name: NSNotification.Name.UITextViewTextDidChange, object: nil)
    }

    override public func draw(_ rect: CGRect) {
        if(self.placeHolder.length > 0) {
            self.placeHolderLabel.frame = CGRect(x: 8, y: 8, width: self.bounds.size.width - 16 , height: 0)
            self.placeHolderLabel.lineBreakMode = NSLineBreakMode.byWordWrapping
            self.placeHolderLabel.numberOfLines = 0
            self.placeHolderLabel.font = self.font
            self.placeHolderLabel.backgroundColor = UIColor.clear
            self.placeHolderLabel.textColor = self.placeHolderColor
            self.placeHolderLabel.alpha = 0
            self.placeHolderLabel.tag = 1

            self.placeHolderLabel.text = self.placeHolder as String
            self.placeHolderLabel.sizeToFit()
            self.addSubview(placeHolderLabel)
        }

        self.sendSubview(toBack: placeHolderLabel)

        if(self.text.utf16.count == 0 && self.placeHolder.length > 0){
            self.viewWithTag(1)?.alpha = 1
        }

        super.draw(rect)
    }

    @objc func textChanged(notification:NSNotification?) -> (Void) {
        if(self.placeHolder.length == 0){
            return
        }

        if(self.text.utf16.count == 0) {
            self.viewWithTag(1)?.alpha = 1
        }else{
            self.viewWithTag(1)?.alpha = 0
        }
    }

}

カスタムビューなのでStoryboardでカスタムクラスを自作のPlaceHolderTextViewに指定しないと関連付けが出来ませんので注意!

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