uitextview placeholder uikit ios
class ViewController: UIViewController {
@IBOutlet weak var textView: UITextView!
let placeholder = "Example: I started my career as a street wear model based in Maryland. After 3 years of working with some of the top companies there, I moved to LA, where I currently reside. I’ve been featured in shows, 12 magazines, commercials, and a number of music videos. Now, Im currently looking to continue working with clothing companies and campaigns."
let start = NSRange(location: 0, length: 0)
override func viewDidLoad() {
super.viewDidLoad()
textView.delegate = self
textView.text = placeholder
}
}
extension ViewController: UITextViewDelegate {
func textViewDidChangeSelection(_ textView: UITextView) {
// Moves cursor to start when tapped on textView with placeholder
if textView.text == placeholder {
textView.selectedRange = start
}
}
func textViewDidChange(_ textView: UITextView) {
// Manages state of text when changed
if textView.text.isEmpty {
textView.text = placeholder
textView.textColor = .lightGray
} else if textView.text != placeholder {
textView.textColor = .black
}
}
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
// Called when you're trying to enter a character (to replace the placeholder)
if textView.text == placeholder {
textView.text = ""
}
return true
}
}
Shiny Shark