Skip to content

Instantly share code, notes, and snippets.

@dm-katsubo
Last active August 24, 2022 11:13
Show Gist options
  • Save dm-katsubo/f70dbdd9c8159b1e7aa62d3b1b79928b to your computer and use it in GitHub Desktop.
Save dm-katsubo/f70dbdd9c8159b1e7aa62d3b1b79928b to your computer and use it in GitHub Desktop.
PlaceholderTextView
final class PlaceholderTextView: UITextView {
private lazy var placeholderLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.backgroundColor = .clear
label.isUserInteractionEnabled = false
label.textColor = .neutralDark600
label.numberOfLines = 0
label.font = .systemFont(ofSize: 14, weight: .medium)
return label
}()
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
setupView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
override var text: String! {
didSet {
placeholderLabel.isHidden = text.isNotEmpty
}
}
override var textContainerInset: UIEdgeInsets {
didSet {
NSLayoutConstraint.activate([
placeholderLabel.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor, constant: textContainerInset.left),
placeholderLabel.trailingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.trailingAnchor, constant: -textContainerInset.right),
placeholderLabel.topAnchor.constraint(equalTo: topAnchor, constant: textContainerInset.top)
])
}
}
// MARK: - Public
var placeholder: String? {
get {
return placeholderLabel.text
}
set {
placeholderLabel.text = newValue
}
}
var placeholderColor: UIColor? {
set {
placeholderLabel.textColor = newValue ?? .neutralDark600
}
get {
return placeholderLabel.textColor
}
}
override func becomeFirstResponder() -> Bool {
placeholderLabel.isHidden = true
return super.becomeFirstResponder()
}
override func resignFirstResponder() -> Bool {
placeholderLabel.isHidden = text.isNotEmpty
return super.resignFirstResponder()
}
// MARK: - Private
private func setupView() {
placeholderLabel.font = font
addSubview(placeholderLabel)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment