Created
July 24, 2016 06:53
-
-
Save maximbilan/f7b7397c0b32264f1afcecc1f762dee2 to your computer and use it in GitHub Desktop.
UITextView Placeholder Example
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 | |
class ViewController: UIViewController { | |
let placeholder = "Placeholder" | |
@IBOutlet weak var textView: UITextView! | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
textView.delegate = self | |
textView.text = placeholder | |
textView.textColor = UIColor.lightGrayColor() | |
textView.selectedTextRange = textView.textRangeFromPosition(textView.beginningOfDocument, toPosition: textView.beginningOfDocument) | |
} | |
} | |
extension ViewController: UITextViewDelegate { | |
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool { | |
let currentText: NSString = textView.text | |
let updatedText = currentText.stringByReplacingCharactersInRange(range, withString:text) | |
if updatedText.isEmpty { | |
textView.text = placeholder | |
textView.textColor = UIColor.lightGrayColor() | |
textView.selectedTextRange = textView.textRangeFromPosition(textView.beginningOfDocument, toPosition: textView.beginningOfDocument) | |
return false | |
} | |
else if textView.textColor == UIColor.lightGrayColor() && !text.isEmpty { | |
textView.text = nil | |
textView.textColor = UIColor.blackColor() | |
} | |
return true | |
} | |
func textViewDidChangeSelection(textView: UITextView) { | |
if self.view.window != nil { | |
if textView.textColor == UIColor.lightGrayColor() { | |
textView.selectedTextRange = textView.textRangeFromPosition(textView.beginningOfDocument, toPosition: textView.beginningOfDocument) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment