Dieser Thread hatte viele Antworten, aber hier ist die Version, die ich bevorzuge.
Es erweitert die vorhandene UITextView
Klasse, ist also leicht wiederverwendbar und es nicht abfangen , die Ereignisse wie textViewDidChange
(die Benutzer-Code brechen könnten, wenn sie bereits diese Ereignisse an anderer Stelle abfängt wurden).
Mit meinem Code (siehe unten) können Sie jedem Ihrer Platzhalter ganz einfach einen Platzhalter hinzufügen UITextViews
:
self.textViewComments.placeholder = @"(Enter some comments here.)";
Wenn Sie diesen neuen Platzhalterwert festlegen, wird stillschweigend ein Zusatz UILabel
zu Ihrem hinzugefügtUITextView
bei Bedarf ausgeblendet / angezeigt:
Okay, um diese Änderungen vorzunehmen, fügen Sie eine "UITextViewHelper.h" -Datei hinzu, die diesen Code enthält:
// UITextViewHelper.h
// Created by Michael Gledhill on 13/02/15.
#import <Foundation/Foundation.h>
@interface UITextView (UITextViewHelper)
@property (nonatomic, strong) NSString* placeholder;
@property (nonatomic, strong) UILabel* placeholderLabel;
@property (nonatomic, strong) NSString* textValue;
-(void)checkIfNeedToDisplayPlaceholder;
@end
... und eine UITextViewHelper.m-Datei, die Folgendes enthält:
// UITextViewHelper.m
// Created by Michael Gledhill on 13/02/15.
//
// This UITextView category allows us to easily display a PlaceHolder string in our UITextView.
// The downside is that, your code needs to set the "textValue" rather than the "text" value to safely set the UITextView's text.
//
#import "UITextViewHelper.h"
#import <objc/runtime.h>
@implementation UITextView (UITextViewHelper)
#define UI_PLACEHOLDER_TEXT_COLOR [UIColor colorWithRed:170.0/255.0 green:170.0/255.0 blue:170.0/255.0 alpha:1.0]
@dynamic placeholder;
@dynamic placeholderLabel;
@dynamic textValue;
-(void)setTextValue:(NSString *)textValue
{
// Change the text of our UITextView, and check whether we need to display the placeholder.
self.text = textValue;
[self checkIfNeedToDisplayPlaceholder];
}
-(NSString*)textValue
{
return self.text;
}
-(void)checkIfNeedToDisplayPlaceholder
{
// If our UITextView is empty, display our Placeholder label (if we have one)
if (self.placeholderLabel == nil)
return;
self.placeholderLabel.hidden = (![self.text isEqualToString:@""]);
}
-(void)onTap
{
// When the user taps in our UITextView, we'll see if we need to remove the placeholder text.
[self checkIfNeedToDisplayPlaceholder];
// Make the onscreen keyboard appear.
[self becomeFirstResponder];
}
-(void)keyPressed:(NSNotification*)notification
{
// The user has just typed a character in our UITextView (or pressed the delete key).
// Do we need to display our Placeholder label ?
[self checkIfNeedToDisplayPlaceholder];
}
#pragma mark - Add a "placeHolder" string to the UITextView class
NSString const *kKeyPlaceHolder = @"kKeyPlaceHolder";
-(void)setPlaceholder:(NSString *)_placeholder
{
// Sets our "placeholder" text string, creates a new UILabel to contain it, and modifies our UITextView to cope with
// showing/hiding the UILabel when needed.
objc_setAssociatedObject(self, &kKeyPlaceHolder, (id)_placeholder, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
self.placeholderLabel = [[UILabel alloc] initWithFrame:self.frame];
self.placeholderLabel.numberOfLines = 1;
self.placeholderLabel.text = _placeholder;
self.placeholderLabel.textColor = UI_PLACEHOLDER_TEXT_COLOR;
self.placeholderLabel.backgroundColor = [UIColor clearColor];
self.placeholderLabel.userInteractionEnabled = true;
self.placeholderLabel.font = self.font;
[self addSubview:self.placeholderLabel];
[self.placeholderLabel sizeToFit];
// Whenever the user taps within the UITextView, we'll give the textview the focus, and hide the placeholder if necessary.
[self addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTap)]];
// Whenever the user types something in the UITextView, we'll see if we need to hide/show the placeholder label.
[[NSNotificationCenter defaultCenter] addObserver:self selector: @selector(keyPressed:) name:UITextViewTextDidChangeNotification object:nil];
[self checkIfNeedToDisplayPlaceholder];
}
-(NSString*)placeholder
{
// Returns our "placeholder" text string
return objc_getAssociatedObject(self, &kKeyPlaceHolder);
}
#pragma mark - Add a "UILabel" to this UITextView class
NSString const *kKeyLabel = @"kKeyLabel";
-(void)setPlaceholderLabel:(UILabel *)placeholderLabel
{
// Stores our new UILabel (which contains our placeholder string)
objc_setAssociatedObject(self, &kKeyLabel, (id)placeholderLabel, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
[[NSNotificationCenter defaultCenter] addObserver:self selector: @selector(keyPressed:) name:UITextViewTextDidChangeNotification object:nil];
[self checkIfNeedToDisplayPlaceholder];
}
-(UILabel*)placeholderLabel
{
// Returns our new UILabel
return objc_getAssociatedObject(self, &kKeyLabel);
}
@end
Ja, es ist viel Code, aber sobald Sie ihn Ihrem Projekt hinzugefügt und die .h-Datei hinzugefügt haben ...
#import "UITextViewHelper.h"
... können Sie problemlos Platzhalter in verwenden UITextViews
.
Es gibt aber einen Fall.
Wenn du das tust:
self.textViewComments.placeholder = @"(Enter some comments here.)";
self.textViewComments.text = @"Ooooh, hello there";
... wird der Platzhalter über dem Text angezeigt. Wenn Sie den text
Wert festlegen , wird keine der regulären Benachrichtigungen aufgerufen, sodass ich nicht herausfinden konnte, wie ich meine Funktion aufrufen soll, um zu entscheiden, ob der Platzhalter ein- oder ausgeblendet werden soll.
Die Lösung besteht darin, textValue
Folgendes festzulegen text
:
self.textViewComments.placeholder = @"(Enter some comments here.)";
self.textViewComments.textValue = @"Ooooh, hello there";
Alternativ können Sie den text
Wert festlegen und dann aufrufen checkIfNeedToDisplayPlaceholder
.
self.textViewComments.text = @"Ooooh, hello there";
[self.textViewComments checkIfNeedToDisplayPlaceholder];
Ich mag solche Lösungen, weil sie die Lücke zwischen dem, was Apple uns bietet, und dem, was wir (als Entwickler) tatsächlich brauchen , "füllen" in unseren Apps . Sie schreiben diesen Code einmal, fügen ihn Ihrer Bibliothek mit "helper" .m / .h-Dateien hinzu, und im Laufe der Zeit wird das SDK tatsächlich weniger frustrierend.
(Ich habe einen ähnlichen Helfer geschrieben, um meinen UITextViews einen "Löschen" -Button hinzuzufügen, eine andere Sache, die ärgerlich in, UITextField
aber nicht in UITextView
... existiert.)