I have a very simple subclass of UITextView that adds the "Placeholder" functionality that you can find native to the Text Field object. Here is my code for the subclass:
import UIKit
import Foundation
@IBDesignable class PlaceholderTextView: UITextView, UITextViewDelegate
{
@IBInspectable var placeholder: String = "" {
didSet {
setPlaceholderText()
}
}
private let placeholderColor: UIColor = UIColor.lightGrayColor()
private var textColorCache: UIColor!
override init(frame: CGRect) {
super.init(frame: frame)
self.delegate = self
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.delegate = self
}
func textViewDidBeginEditing(textView: UITextView) {
if textView.text == placeholder {
textView.text = ""
textView.textColor = textColorCache
}
}
func textViewDidEndEditing(textView: UITextView) {
if textView.text == "" && placeholder != "" {
setPlaceholderText()
}
}
func setPlaceholderText() {
if placeholder != "" {
if textColorCache == nil { textColorCache = self.textColor }
self.textColor = placeholderColor
self.text = placeholder
}
}
}
After changing the class for the UITextView
object in the Identity Inspector to PlaceholderTextView
, I can set the Placeholder
property just fine in the Attribute Inspector. The code works great when running the app, but does not display the placeholder text in the interface builder. I also get the following non-blocking errors (I assume this is why it's not rendering at design time):
error: IB Designables: Failed to update auto layout status: Interface Builder Cocoa Touch Tool crashed
error: IB Designables: Failed to render instance of PlaceholderTextView: Rendering the view took longer than 200 ms. Your drawing code may suffer from slow performance.
I'm not able to figure out what is causing these errors. The second error doesn't make any sense, as I'm not even overriding drawRect(). Any ideas?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…