Created
January 11, 2017 15:26
-
-
Save Erkened/275fccddf411ac949b144550ac6a4386 to your computer and use it in GitHub Desktop.
A UITextView subclass with placeholder. Swift 3.0
This file contains hidden or 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
// | |
// UITextViewWithPlaceholder.swift | |
// Repnote | |
// | |
// Created by John Neumann on 11/01/2017. | |
// Copyright © 2017 Audioy. All rights reserved. | |
// | |
import UIKit | |
class UITextViewWithPlaceholder: UITextView { | |
private var originalTextColour: UIColor = UIColor.black | |
private var placeholderTextColour: UIColor = UIColor(red: 0, green: 0, blue: 0.098, alpha: 0.22) | |
var placeholder:String?{ | |
didSet{ | |
if let placeholder = placeholder{ | |
text = placeholder | |
} | |
} | |
} | |
override internal var text: String? { | |
didSet{ | |
textColor = originalTextColour | |
if text == placeholder{ | |
textColor = placeholderTextColour | |
} | |
} | |
} | |
override internal var textColor: UIColor?{ | |
didSet{ | |
if let textColor = textColor, textColor != placeholderTextColour{ | |
originalTextColour = textColor | |
if text == placeholder{ | |
self.textColor = placeholderTextColour | |
} | |
} | |
} | |
} | |
override init(frame: CGRect, textContainer: NSTextContainer?) { | |
super.init(frame: frame, textContainer: textContainer) | |
// Remove the padding top and left of the text view | |
self.textContainer.lineFragmentPadding = 0 | |
self.textContainerInset = UIEdgeInsets.zero | |
// Listen for text view did begin editing | |
NotificationCenter.default.addObserver(self, selector: #selector(removePlaceholder), name: NSNotification.Name.UITextViewTextDidBeginEditing, object: nil) | |
// Listen for text view did end editing | |
NotificationCenter.default.addObserver(self, selector: #selector(addPlaceholder), name: NSNotification.Name.UITextViewTextDidEndEditing, object: nil) | |
} | |
required init?(coder aDecoder: NSCoder) { | |
fatalError("init(coder:) has not been implemented") | |
} | |
@objc private func removePlaceholder(){ | |
if text == placeholder{ | |
text = "" | |
} | |
} | |
@objc private func addPlaceholder(){ | |
if text?.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) == "" { | |
text = placeholder | |
} | |
} | |
deinit { | |
NotificationCenter.default.removeObserver(self) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment