Created
October 13, 2017 07:34
-
-
Save keitaoouchi/f0dc20d0d1c138c5cc0aa554130d9b23 to your computer and use it in GitHub Desktop.
PlaceholderTextView.swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
@IBDesignable | |
final class PlaceholderTextView: UITextView, UITextViewDelegate { | |
private let _TAG = 100 | |
override open var bounds: CGRect { | |
didSet { | |
self.resizePlaceholder() | |
} | |
} | |
override var font: UIFont? { | |
didSet { | |
self.resizePlaceholder() | |
} | |
} | |
@IBInspectable var placeholder: String? { | |
get { | |
if let label = self.viewWithTag(_TAG) as? UILabel { | |
return label.text | |
} else { | |
return nil | |
} | |
} | |
set { | |
if let label = self.viewWithTag(_TAG) as? UILabel { | |
label.font = self.font | |
label.text = newValue | |
label.sizeToFit() | |
} else { | |
self.addPlaceholder(with: newValue) | |
} | |
} | |
} | |
public func textViewDidChange(_ textView: UITextView) { | |
if let label = self.viewWithTag(_TAG) as? UILabel { | |
label.isHidden = !self.text.isEmpty | |
} | |
} | |
private func resizePlaceholder() { | |
if let label = self.viewWithTag(_TAG) as? UILabel { | |
label.font = self.font | |
label.sizeToFit() | |
let x = self.textContainer.lineFragmentPadding | |
let y = self.textContainerInset.top - 2 | |
let width = self.frame.width - (x * 2) | |
let height = label.frame.height | |
label.frame = CGRect(x: x, y: y, width: width, height: height) | |
} | |
} | |
private func addPlaceholder(with text: String?) { | |
guard let text = text else { return } | |
let label = UILabel() | |
label.text = text | |
label.textColor = UIColor(hex: "#C7C7CD") | |
label.tag = _TAG | |
label.isHidden = !self.text.isEmpty | |
self.addSubview(label) | |
self.resizePlaceholder() | |
self.delegate = self | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment