Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
//
// PlaceHolderedTextView.swift
// Musubi
//
// Created by はるふ on 2016/11/29.
// Copyright © 2016年 はるふ. All rights reserved.
//
import UIKit
@IBDesignable
class PlaceHolderedTextView: UITextView {
// MARK: stored properties
@IBInspectable var placeHolder = ""
@IBInspectable var placeHolderColor = UIColor.lightGray
private lazy var placeHolderLayer: CATextLayer = {
let layer = CATextLayer()
layer.fontSize = self.font?.pointSize ?? UIFont.systemFontSize
layer.frame = CGRect(x: self.textContainerInset.left + self.textContainer.lineFragmentPadding, y: self.textContainerInset.top, width: self.frame.width, height: layer.fontSize+10)
layer.string = self.placeHolder
layer.foregroundColor = self.placeHolderColor.cgColor
layer.contentsScale = UIScreen.main.scale
layer.alignmentMode = kCAAlignmentLeft
self.layer.addSublayer(layer)
return layer
}()
private func updateLayer() {
DispatchQueue.main.async { [weak self] in
self?.placeHolderLayer.isHidden = !(self?.text?.isEmpty ?? true)
}
}
func onChangedText(_ notification: NSNotification?) {
updateLayer()
}
// MARK: Observer
private func addObserver() {
updateLayer()
NotificationCenter.default.addObserver(self, selector: #selector(self.onChangedText(_:)), name: NSNotification.Name.UITextViewTextDidChange, object: self)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
addObserver()
}
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
addObserver()
}
// iOS 9.0以降なら不要
// http://qiita.com/mono0926/items/754c5d2dbe431542c75e
deinit {
NotificationCenter.default.removeObserver(self)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment