Skip to content

Instantly share code, notes, and snippets.

@KyleLeneau
Last active October 31, 2015 21:08
Show Gist options
  • Save KyleLeneau/434523e3c890ec4d4031 to your computer and use it in GitHub Desktop.
Save KyleLeneau/434523e3c890ec4d4031 to your computer and use it in GitHub Desktop.
Quick implementation of a UITextView that supports placeholder text and cursor position just like UITextField
class ExampleViewController: UIViewController, UITextViewDelegate {
@IBOutlet var placeholderInput: UIPlaceHolderTextView! {
didSet {
placeholderInput.placeholder = "Your custom placeholder text here"
placeholderInput.placeholderColor = UIColor.redColor() // what ever color you want here too
placeholderInput.text = placeholderInput.placeholder
placeholderInput.textColor = placeholderInput.placeholderColor
placeholderInput.selectedTextRange = placeholderInput.textRangeFromPosition(placeholderInput.beginningOfDocument, toPosition: placeholderInput.beginningOfDocument)
placeholderInput.delegate = self
}
}
// MARK: UITextViewDelegate
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
guard let placeHolderTextView = textView as? UIPlaceHolderTextView else { return true }
// Combine the textView text and the replacement text to create the updated text string
let currentText: NSString = placeHolderTextView.text
let updatedText = currentText.stringByReplacingCharactersInRange(range, withString: text)
if updatedText.isEmpty {
// If updated text view will be empty, add the placeholder and set the cursor to the beginning of the text view
placeHolderTextView.text = placeHolderTextView.placeholder
placeHolderTextView.textColor = placeHolderTextView.placeholderColor
placeHolderTextView.selectedTextRange = placeHolderTextView.textRangeFromPosition(placeHolderTextView.beginningOfDocument, toPosition: placeHolderTextView.beginningOfDocument)
return false
}
else if placeHolderTextView.textColor == placeHolderTextView.placeholderColor && !text.isEmpty {
// Else if the text view's placeholder is showing and the length of the replacement string is
// greater than 0, clear the text view and set its color to black to prepare for the user's entry
textView.text = nil
textView.textColor = UIColor.blackColor()
}
return true
}
func textViewDidChangeSelection(textView: UITextView) {
if let placeHolderTextView = textView as? UIPlaceHolderTextView where self.view.window != nil {
if placeHolderTextView.textColor == placeHolderTextView.placeholderColor {
placeHolderTextView.selectedTextRange = placeHolderTextView.textRangeFromPosition(placeHolderTextView.beginningOfDocument, toPosition: placeHolderTextView.beginningOfDocument)
}
}
}
}
class UIPlaceHolderTextView: UITextView {
var placeholder = "Placeholder"
var placeholderColor = UIColor.lightGrayColor()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment