Last active
November 6, 2018 14:52
-
-
Save fewlinesofcode/e395d5ea0f0e60634f80aab542a87946 to your computer and use it in GitHub Desktop.
The idea was to make the simplest possible solution which allows to use placeholders of different colors, resizes to placeholders size, will not overwrite a `delegate` meanwhile keeping all `UITextView` functions work as expected.
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
// | |
// Created by Oleksandr Glagoliev on 05/11/2018. | |
// Copyright © 2018 Oleksandr Glagoliev. All rights reserved. | |
// | |
import UIKit | |
class PlaceholderTextView: UITextView { | |
var placeholderColor: UIColor = .lightGray | |
var defaultTextColor: UIColor = .black | |
private var isShowingPlaceholder = false { | |
didSet { | |
if isShowingPlaceholder { | |
text = placeholder | |
textColor = placeholderColor | |
} else { | |
textColor = defaultTextColor | |
} | |
} | |
} | |
var placeholder: String? { | |
didSet { | |
isShowingPlaceholder = !hasText | |
} | |
} | |
@objc private func textViewDidBeginEditing(notification: Notification) { | |
textColor = defaultTextColor | |
if isShowingPlaceholder { text = nil } | |
} | |
@objc private func textViewDidEndEditing(notification: Notification) { | |
isShowingPlaceholder = !hasText | |
} | |
// MARK: - Construction - | |
override init(frame: CGRect, textContainer: NSTextContainer?) { | |
super.init(frame: frame, textContainer: textContainer) | |
setup() | |
} | |
required init?(coder aDecoder: NSCoder) { | |
super.init(coder: aDecoder) | |
setup() | |
} | |
private func setup() { | |
NotificationCenter.default.addObserver(self, selector: #selector(textViewDidBeginEditing(notification:)), name: UITextView.textDidBeginEditingNotification, object: self) | |
NotificationCenter.default.addObserver(self, selector: #selector(textViewDidEndEditing(notification:)), name: UITextView.textDidEndEditingNotification, object: self) | |
} | |
// MARK: - Destruction - | |
deinit { NotificationCenter.default.removeObserver(self) } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment