我的应用程序使用UITextView
。现在我希望UITextView
的占位符类似于您为UITextField
设置的占位符。
怎么做?
答案 0 :(得分:664)
我对bcd的解决方案做了一些小修改,允许从Xib
文件进行初始化,文本换行,并保持背景颜色。希望这会给别人带来麻烦。
<强> UIPlaceHolderTextView.h:强>
#import <Foundation/Foundation.h>
IB_DESIGNABLE
@interface UIPlaceHolderTextView : UITextView
@property (nonatomic, retain) IBInspectable NSString *placeholder;
@property (nonatomic, retain) IBInspectable UIColor *placeholderColor;
-(void)textChanged:(NSNotification*)notification;
@end
<强> UIPlaceHolderTextView.m:强>
#import "UIPlaceHolderTextView.h"
@interface UIPlaceHolderTextView ()
@property (nonatomic, retain) UILabel *placeHolderLabel;
@end
@implementation UIPlaceHolderTextView
CGFloat const UI_PLACEHOLDER_TEXT_CHANGED_ANIMATION_DURATION = 0.25;
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
#if __has_feature(objc_arc)
#else
[_placeHolderLabel release]; _placeHolderLabel = nil;
[_placeholderColor release]; _placeholderColor = nil;
[_placeholder release]; _placeholder = nil;
[super dealloc];
#endif
}
- (void)awakeFromNib
{
[super awakeFromNib];
// Use Interface Builder User Defined Runtime Attributes to set
// placeholder and placeholderColor in Interface Builder.
if (!self.placeholder) {
[self setPlaceholder:@""];
}
if (!self.placeholderColor) {
[self setPlaceholderColor:[UIColor lightGrayColor]];
}
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged:) name:UITextViewTextDidChangeNotification object:nil];
}
- (id)initWithFrame:(CGRect)frame
{
if( (self = [super initWithFrame:frame]) )
{
[self setPlaceholder:@""];
[self setPlaceholderColor:[UIColor lightGrayColor]];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged:) name:UITextViewTextDidChangeNotification object:nil];
}
return self;
}
- (void)textChanged:(NSNotification *)notification
{
if([[self placeholder] length] == 0)
{
return;
}
[UIView animateWithDuration:UI_PLACEHOLDER_TEXT_CHANGED_ANIMATION_DURATION animations:^{
if([[self text] length] == 0)
{
[[self viewWithTag:999] setAlpha:1];
}
else
{
[[self viewWithTag:999] setAlpha:0];
}
}];
}
- (void)setText:(NSString *)text {
[super setText:text];
[self textChanged:nil];
}
- (void)drawRect:(CGRect)rect
{
if( [[self placeholder] length] > 0 )
{
if (_placeHolderLabel == nil )
{
_placeHolderLabel = [[UILabel alloc] initWithFrame:CGRectMake(8,8,self.bounds.size.width - 16,0)];
_placeHolderLabel.lineBreakMode = NSLineBreakByWordWrapping;
_placeHolderLabel.numberOfLines = 0;
_placeHolderLabel.font = self.font;
_placeHolderLabel.backgroundColor = [UIColor clearColor];
_placeHolderLabel.textColor = self.placeholderColor;
_placeHolderLabel.alpha = 0;
_placeHolderLabel.tag = 999;
[self addSubview:_placeHolderLabel];
}
_placeHolderLabel.text = self.placeholder;
[_placeHolderLabel sizeToFit];
[self sendSubviewToBack:_placeHolderLabel];
}
if( [[self text] length] == 0 && [[self placeholder] length] > 0 )
{
[[self viewWithTag:999] setAlpha:1];
}
[super drawRect:rect];
}
@end
答案 1 :(得分:617)
简单来说,只需使用以下UITextView
方法在UITextViewDelegate
中创建占位符文字:
- (void)textViewDidBeginEditing:(UITextView *)textView
{
if ([textView.text isEqualToString:@"placeholder text here..."]) {
textView.text = @"";
textView.textColor = [UIColor blackColor]; //optional
}
[textView becomeFirstResponder];
}
- (void)textViewDidEndEditing:(UITextView *)textView
{
if ([textView.text isEqualToString:@""]) {
textView.text = @"placeholder text here...";
textView.textColor = [UIColor lightGrayColor]; //optional
}
[textView resignFirstResponder];
}
请记住将myUITextView
设置为创建时的确切文字,例如
UITextView *myUITextView = [[UITextView alloc] init];
myUITextView.delegate = self;
myUITextView.text = @"placeholder text here...";
myUITextView.textColor = [UIColor lightGrayColor]; //optional
并在包含这些方法之前将父类设为UITextViewDelegate
,例如
@interface MyClass () <UITextViewDelegate>
@end
Swift 3.1代码
func textViewDidBeginEditing(_ textView: UITextView)
{
if (textView.text == "placeholder text here..." && textView.textColor == .lightGray)
{
textView.text = ""
textView.textColor = .black
}
textView.becomeFirstResponder() //Optional
}
func textViewDidEndEditing(_ textView: UITextView)
{
if (textView.text == "")
{
textView.text = "placeholder text here..."
textView.textColor = .lightGray
}
textView.resignFirstResponder()
}
请记住将myUITextView
设置为创建时的确切文字,例如
let myUITextView = UITextView.init()
myUITextView.delegate = self
myUITextView.text = "placeholder text here..."
myUITextView.textColor = .lightGray
并在包含这些方法之前将父类设为UITextViewDelegate
,例如
class MyClass: UITextViewDelegate
{
}
答案 2 :(得分:119)
我对发布的任何解决方案都不太满意,因为它们有点沉重。向视图添加视图并不是很理想(特别是在drawRect:
中)。他们都有泄漏,这也是不可接受的。
以下是我的解决方案:SAMTextView
SAMTextView.h
//
// SAMTextView.h
// SAMTextView
//
// Created by Sam Soffes on 8/18/10.
// Copyright 2010-2013 Sam Soffes. All rights reserved.
//
#import <UIKit/UIKit.h>
/**
UITextView subclass that adds placeholder support like UITextField has.
*/
@interface SAMTextView : UITextView
/**
The string that is displayed when there is no other text in the text view.
The default value is `nil`.
*/
@property (nonatomic, strong) NSString *placeholder;
/**
The color of the placeholder.
The default is `[UIColor lightGrayColor]`.
*/
@property (nonatomic, strong) UIColor *placeholderTextColor;
/**
Returns the drawing rectangle for the text views’s placeholder text.
@param bounds The bounding rectangle of the receiver.
@return The computed drawing rectangle for the placeholder text.
*/
- (CGRect)placeholderRectForBounds:(CGRect)bounds;
@end
SAMTextView.m
//
// SAMTextView.m
// SAMTextView
//
// Created by Sam Soffes on 8/18/10.
// Copyright 2010-2013 Sam Soffes. All rights reserved.
//
#import "SAMTextView.h"
@implementation SAMTextView
#pragma mark - Accessors
@synthesize placeholder = _placeholder;
@synthesize placeholderTextColor = _placeholderTextColor;
- (void)setText:(NSString *)string {
[super setText:string];
[self setNeedsDisplay];
}
- (void)insertText:(NSString *)string {
[super insertText:string];
[self setNeedsDisplay];
}
- (void)setAttributedText:(NSAttributedString *)attributedText {
[super setAttributedText:attributedText];
[self setNeedsDisplay];
}
- (void)setPlaceholder:(NSString *)string {
if ([string isEqual:_placeholder]) {
return;
}
_placeholder = string;
[self setNeedsDisplay];
}
- (void)setContentInset:(UIEdgeInsets)contentInset {
[super setContentInset:contentInset];
[self setNeedsDisplay];
}
- (void)setFont:(UIFont *)font {
[super setFont:font];
[self setNeedsDisplay];
}
- (void)setTextAlignment:(NSTextAlignment)textAlignment {
[super setTextAlignment:textAlignment];
[self setNeedsDisplay];
}
#pragma mark - NSObject
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self name:UITextViewTextDidChangeNotification object:self];
}
#pragma mark - UIView
- (id)initWithCoder:(NSCoder *)aDecoder {
if ((self = [super initWithCoder:aDecoder])) {
[self initialize];
}
return self;
}
- (id)initWithFrame:(CGRect)frame {
if ((self = [super initWithFrame:frame])) {
[self initialize];
}
return self;
}
- (void)drawRect:(CGRect)rect {
[super drawRect:rect];
if (self.text.length == 0 && self.placeholder) {
rect = [self placeholderRectForBounds:self.bounds];
UIFont *font = self.font ? self.font : self.typingAttributes[NSFontAttributeName];
// Draw the text
[self.placeholderTextColor set];
[self.placeholder drawInRect:rect withFont:font lineBreakMode:NSLineBreakByTruncatingTail alignment:self.textAlignment];
}
}
#pragma mark - Placeholder
- (CGRect)placeholderRectForBounds:(CGRect)bounds {
// Inset the rect
CGRect rect = UIEdgeInsetsInsetRect(bounds, self.contentInset);
if (self.typingAttributes) {
NSParagraphStyle *style = self.typingAttributes[NSParagraphStyleAttributeName];
if (style) {
rect.origin.x += style.headIndent;
rect.origin.y += style.firstLineHeadIndent;
}
}
return rect;
}
#pragma mark - Private
- (void)initialize {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged:) name:UITextViewTextDidChangeNotification object:self];
self.placeholderTextColor = [UIColor colorWithWhite:0.702f alpha:1.0f];
}
- (void)textChanged:(NSNotification *)notification {
[self setNeedsDisplay];
}
@end
它比其他人简单得多,因为它不使用子视图(或有泄漏)。随意使用它。
更新11/10/11:现在已经记录并支持在Interface Builder中使用。
更新11/24/13:指向新的回购。
答案 3 :(得分:52)
您可以执行的操作是在text
属性中设置包含一些初始值的文本视图,并将textColor
更改为[UIColor grayColor]
或类似的内容。然后,只要文本视图变得可编辑,清除文本并显示光标,如果文本字段再次为空,请将占位符文本放回原位。根据需要将颜色更改为[UIColor blackColor]
。
它与UITextField中的占位符功能不完全相同,但它很接近。
答案 4 :(得分:49)
我发现自己很容易模仿一个占位符
修改强>
更改if语句以比较标签而不是文本。如果用户删除了他们的文本,也可能会意外删除占位符@"Foobar placeholder"
的一部分。这意味着如果用户重新输入textView以下委托方法-(BOOL) textViewShouldBeginEditing:(UITextView *) textView
,则无法正常工作正如所料。我尝试使用if语句中的文本颜色进行比较,但发现界面构建器中的浅灰色设置与使用[UIColor lightGreyColor]
的代码中设置的浅灰色颜色不同
- (BOOL) textViewShouldBeginEditing:(UITextView *)textView
{
if(textView.tag == 0) {
textView.text = @"";
textView.textColor = [UIColor blackColor];
textView.tag = 1;
}
return YES;
}
当键盘返回并且[textView length] == 0
时,也可以重置占位符文本。编辑:
只是为了让最后一部分更清晰 - 以下是如何设置占位符文本:
- (void)textViewDidChange:(UITextView *)textView
{
if([textView.text length] == 0)
{
textView.text = @"Foobar placeholder";
textView.textColor = [UIColor lightGrayColor];
textView.tag = 0;
}
}
答案 5 :(得分:46)
您可以在UITextView
上设置标签
[UITextView addSubView:lblPlaceHoldaer];
并将其隐藏在TextViewdidChange
方法上。
这是简单的&amp;简单的方法。
答案 6 :(得分:44)
如果有人需要Swift解决方案:
将UITextViewDelegate添加到您的班级
var placeHolderText = "Placeholder Text..."
override func viewDidLoad() {
super.viewDidLoad()
textView.delegate = self
}
func textViewShouldBeginEditing(textView: UITextView) -> Bool {
self.textView.textColor = .black
if(self.textView.text == placeHolderText) {
self.textView.text = ""
}
return true
}
func textViewDidEndEditing(textView: UITextView) {
if(textView.text == "") {
self.textView.text = placeHolderText
self.textView.textColor = .lightGray
}
}
override func viewWillAppear(animated: Bool) {
if(currentQuestion.answerDisplayValue == "") {
self.textView.text = placeHolderText
self.textView.textColor = .lightGray
} else {
self.textView.text = "xxx" // load default text / or stored
self.textView.textColor = .black
}
}
答案 7 :(得分:42)
简单 Swift 3 解决方案
将UITextViewDelegate
添加到您的班级
设置yourTextView.delegate = self
创建placeholderLabel
并将其放在yourTextView
现在只需placeholderLabel.alpha
上的textViewDidChange
动画:
func textViewDidChange(_ textView: UITextView) {
let newAlpha: CGFloat = textView.text.isEmpty ? 1 : 0
if placeholderLabel.alpha != newAlpha {
UIView.animate(withDuration: 0.3) {
self.placeholderLabel.alpha = newAlpha
}
}
}
您可能必须使用placeholderLabel
位置才能正确设置,但这不应该太难
答案 8 :(得分:23)
我扩展了KmKndy的答案,以便占位符保持可见,直到用户开始编辑UITextView
而不是点击它。这反映了Twitter和Facebook应用程序中的功能。如果用户直接键入或粘贴文本,我的解决方案不要求您进行子类化和工作!
- (void)textViewDidChangeSelection:(UITextView *)textView{
if ([textView.text isEqualToString:@"What's happening?"] && [textView.textColor isEqual:[UIColor lightGrayColor]])[textView setSelectedRange:NSMakeRange(0, 0)];
}
- (void)textViewDidBeginEditing:(UITextView *)textView{
[textView setSelectedRange:NSMakeRange(0, 0)];
}
- (void)textViewDidChange:(UITextView *)textView
{
if (textView.text.length != 0 && [[textView.text substringFromIndex:1] isEqualToString:@"What's happening?"] && [textView.textColor isEqual:[UIColor lightGrayColor]]){
textView.text = [textView.text substringToIndex:1];
textView.textColor = [UIColor blackColor]; //optional
}
else if(textView.text.length == 0){
textView.text = @"What's happening?";
textView.textColor = [UIColor lightGrayColor];
[textView setSelectedRange:NSMakeRange(0, 0)];
}
}
- (void)textViewDidEndEditing:(UITextView *)textView
{
if ([textView.text isEqualToString:@""]) {
textView.text = @"What's happening?";
textView.textColor = [UIColor lightGrayColor]; //optional
}
[textView resignFirstResponder];
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
if (textView.text.length > 1 && [textView.text isEqualToString:@"What's happening?"]) {
textView.text = @"";
textView.textColor = [UIColor blackColor];
}
return YES;
}
请记住在创建时使用确切的文本设置myUITextView,例如
UITextView *myUITextView = [[UITextView alloc] init];
myUITextView.delegate = self;
myUITextView.text = @"What's happening?";
myUITextView.textColor = [UIColor lightGrayColor]; //optional
并在包含这些方法之前使父类成为UITextView委托,例如
@interface MyClass () <UITextViewDelegate>
@end
答案 9 :(得分:20)
我建议使用SZTextView
。
https://github.com/glaszig/SZTextView
从UITextView
添加您的默认storyboard
,然后将其自定义类更改为SZTextView
,如下所示
然后您会在Attribute Inspector
答案 10 :(得分:17)
下面是一个Swift端口的“SAMTextView”ObjC代码,作为对该问题的第一批回复之一。我在iOS 8上测试了它。我调整了一些东西,包括占位符文本放置的边界偏移量,因为原始版本太高而且太远了(在该帖子的其中一条评论中使用了建议)。
我知道有很多简单的解决方案,但我喜欢子类化UITextView的方法,因为它是可重用的,而且我不需要使用机制来混淆类。
Swift 2.2:
import UIKit
class PlaceholderTextView: UITextView {
@IBInspectable var placeholderColor: UIColor = UIColor.lightGrayColor()
@IBInspectable var placeholderText: String = ""
override var font: UIFont? {
didSet {
setNeedsDisplay()
}
}
override var contentInset: UIEdgeInsets {
didSet {
setNeedsDisplay()
}
}
override var textAlignment: NSTextAlignment {
didSet {
setNeedsDisplay()
}
}
override var text: String? {
didSet {
setNeedsDisplay()
}
}
override var attributedText: NSAttributedString? {
didSet {
setNeedsDisplay()
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setUp()
}
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
}
private func setUp() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(PlaceholderTextView.textChanged(_:)),
name: UITextViewTextDidChangeNotification, object: self)
}
func textChanged(notification: NSNotification) {
setNeedsDisplay()
}
func placeholderRectForBounds(bounds: CGRect) -> CGRect {
var x = contentInset.left + 4.0
var y = contentInset.top + 9.0
let w = frame.size.width - contentInset.left - contentInset.right - 16.0
let h = frame.size.height - contentInset.top - contentInset.bottom - 16.0
if let style = self.typingAttributes[NSParagraphStyleAttributeName] as? NSParagraphStyle {
x += style.headIndent
y += style.firstLineHeadIndent
}
return CGRect(x: x, y: y, width: w, height: h)
}
override func drawRect(rect: CGRect) {
if text!.isEmpty && !placeholderText.isEmpty {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = textAlignment
let attributes: [ String: AnyObject ] = [
NSFontAttributeName : font!,
NSForegroundColorAttributeName : placeholderColor,
NSParagraphStyleAttributeName : paragraphStyle]
placeholderText.drawInRect(placeholderRectForBounds(bounds), withAttributes: attributes)
}
super.drawRect(rect)
}
}
Swift 4.2:
import UIKit
class PlaceholderTextView: UITextView {
@IBInspectable var placeholderColor: UIColor = UIColor.lightGray
@IBInspectable var placeholderText: String = ""
override var font: UIFont? {
didSet {
setNeedsDisplay()
}
}
override var contentInset: UIEdgeInsets {
didSet {
setNeedsDisplay()
}
}
override var textAlignment: NSTextAlignment {
didSet {
setNeedsDisplay()
}
}
override var text: String? {
didSet {
setNeedsDisplay()
}
}
override var attributedText: NSAttributedString? {
didSet {
setNeedsDisplay()
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setUp()
}
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
}
private func setUp() {
NotificationCenter.default.addObserver(self,
selector: #selector(self.textChanged(notification:)),
name: Notification.Name("UITextViewTextDidChangeNotification"),
object: nil)
}
@objc func textChanged(notification: NSNotification) {
setNeedsDisplay()
}
func placeholderRectForBounds(bounds: CGRect) -> CGRect {
var x = contentInset.left + 4.0
var y = contentInset.top + 9.0
let w = frame.size.width - contentInset.left - contentInset.right - 16.0
let h = frame.size.height - contentInset.top - contentInset.bottom - 16.0
if let style = self.typingAttributes[NSAttributedString.Key.paragraphStyle] as? NSParagraphStyle {
x += style.headIndent
y += style.firstLineHeadIndent
}
return CGRect(x: x, y: y, width: w, height: h)
}
override func draw(_ rect: CGRect) {
if text!.isEmpty && !placeholderText.isEmpty {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = textAlignment
let attributes: [NSAttributedString.Key: Any] = [
NSAttributedString.Key(rawValue: NSAttributedString.Key.font.rawValue) : font!,
NSAttributedString.Key(rawValue: NSAttributedString.Key.foregroundColor.rawValue) : placeholderColor,
NSAttributedString.Key(rawValue: NSAttributedString.Key.paragraphStyle.rawValue) : paragraphStyle]
placeholderText.draw(in: placeholderRectForBounds(bounds: bounds), withAttributes: attributes)
}
super.draw(rect)
}
}
答案 11 :(得分:12)
这是一种更简单的解决方案,其行为与UITextField的占位符完全相同,但不需要绘制自定义视图或辞职第一响应者。
- (void) textViewDidChange:(UITextView *)textView{
if (textView.text.length == 0){
textView.textColor = [UIColor lightGrayColor];
textView.text = placeholderText;
[textView setSelectedRange:NSMakeRange(0, 0)];
isPlaceholder = YES;
} else if (isPlaceholder && ![textView.text isEqualToString:placeholderText]) {
textView.text = [textView.text substringToIndex:1];
textView.textColor = [UIColor blackColor];
isPlaceholder = NO;
}
}
(else if语句中的第二次检查是针对没有输入任何内容且用户按退格键的情况)
只需将您的类设置为UITextViewDelegate即可。在viewDidLoad中,您应该初始化为
- (void) viewDidLoad{
// initialize placeholder text
placeholderText = @"some placeholder";
isPlaceholder = YES;
self.someTextView.text = placeholderText;
self.someTextView.textColor = [UIColor lightGrayColor];
[self.someTextView setSelectedRange:NSMakeRange(0, 0)];
// assign UITextViewDelegate
self.someTextView.delegate = self;
}
答案 12 :(得分:12)
这就是我做到的:
UITextView2.h
#import <UIKit/UIKit.h>
@interface UITextView2 : UITextView <UITextViewDelegate> {
NSString *placeholder;
UIColor *placeholderColor;
}
@property(nonatomic, retain) NSString *placeholder;
@property(nonatomic, retain) UIColor *placeholderColor;
-(void)textChanged:(NSNotification*)notif;
@end
UITextView2.m
@implementation UITextView2
@synthesize placeholder, placeholderColor;
- (id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
[self setPlaceholder:@""];
[self setPlaceholderColor:[UIColor lightGrayColor]];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged:) name:UITextViewTextDidChangeNotification object:nil];
}
return self;
}
-(void)textChanged:(NSNotification*)notif {
if ([[self placeholder] length]==0)
return;
if ([[self text] length]==0) {
[[self viewWithTag:999] setAlpha:1];
} else {
[[self viewWithTag:999] setAlpha:0];
}
}
- (void)drawRect:(CGRect)rect {
if ([[self placeholder] length]>0) {
UILabel *l = [[UILabel alloc] initWithFrame:CGRectMake(8, 8, 0, 0)];
[l setFont:self.font];
[l setTextColor:self.placeholderColor];
[l setText:self.placeholder];
[l setAlpha:0];
[l setTag:999];
[self addSubview:l];
[l sizeToFit];
[self sendSubviewToBack:l];
[l release];
}
if ([[self text] length]==0 && [[self placeholder] length]>0) {
[[self viewWithTag:999] setAlpha:1];
}
[super drawRect:rect];
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];
}
@end
答案 13 :(得分:10)
很抱歉再添加一个答案,但我只是把这样的东西拉掉了,这就创造了最接近UITextField的占位符。
希望这有助于某人。
-(void)textViewDidChange:(UITextView *)textView{
if(textView.textColor == [UIColor lightGrayColor]){
textView.textColor = [UIColor blackColor]; // look at the comment section in this answer
textView.text = [textView.text substringToIndex: 0];// look at the comment section in this answer
}else if(textView.text.length == 0){
textView.text = @"This is some placeholder text.";
textView.textColor = [UIColor lightGrayColor];
textView.selectedRange = NSMakeRange(0, 0);
}
}
-(void)textViewDidChangeSelection:(UITextView *)textView{
if(textView.textColor == [UIColor lightGrayColor] && (textView.selectedRange.location != 0 || textView.selectedRange.length != 0)){
textView.selectedRange = NSMakeRange(0, 0);
}
}
答案 14 :(得分:9)
您可以使用IQKeyboard Manager中提供的IQTextView,它易于使用,只需将textview的set类集成到IQTextView,您可以使用其属性设置您想要的颜色的占位符标签。 您可以从IQKeyboardManager
下载该库或者您可以从cocoapods安装它。
答案 15 :(得分:7)
在某些代码行中使用它的简单方法:
将一个标签带到.nib中的UITextView 将此标签与您的代码相关联, 之后。
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
if (range.location>0 || text.length!=0) {
placeholderLabel1.hidden = YES;
}else{
placeholderLabel1.hidden = NO;
}
return YES;
}
答案 16 :(得分:7)
我修改了Sam Soffes的实现以与iOS7一起使用:
- (void)drawRect:(CGRect)rect
{
[super drawRect:rect];
if (_shouldDrawPlaceholder)
{
UIEdgeInsets insets = self.textContainerInset;
CGRect placeholderRect = CGRectMake(
insets.left + self.textContainer.lineFragmentPadding,
insets.top,
self.frame.size.width - insets.left - insets.right,
self.frame.size.height - insets.top - insets.bottom);
[_placeholderText drawWithRect:placeholderRect
options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingTruncatesLastVisibleLine
attributes:self.placeholderAttributes
context:nil];
}
}
- (NSDictionary *)placeholderAttributes
{
if (_placeholderAttributes == nil)
{
_placeholderAttributes = @
{
NSFontAttributeName : self.font,
NSForegroundColorAttributeName : self.placeholderColor
};
}
return _placeholderAttributes;
}
请记住在可能会更改字体的方法和可能影响它们的其他方面设置_placeholderAttribues = nil
。您可能还想跳过属性字典的“懒惰”制作,如果这不会给您带来麻烦。
修改强>
如果您希望占位符在自动布局动画等之后看起来不错,请记住在重写的setBounds版本中调用setNeedsDisplay。
答案 17 :(得分:6)
您还可以创建一个新类TextViewWithPlaceholder作为UITextView的子类。
(这段代码很粗糙 - 但我认为它是在正确的轨道上。)
@interface TextViewWithPlaceholder : UITextView
{
NSString *placeholderText; // make a property
UIColor *placeholderColor; // make a property
UIColor *normalTextColor; // cache text color here whenever you switch to the placeholderColor
}
- (void) setTextColor: (UIColor*) color
{
normalTextColor = color;
[super setTextColor: color];
}
- (void) updateForTextChange
{
if ([self.text length] == 0)
{
normalTextColor = self.textColor;
self.textColor = placeholderColor;
self.text = placeholderText;
}
else
{
self.textColor = normalTextColor;
}
}
在你的代表中,添加:
- (void)textViewDidChange:(UITextView *)textView
{
if ([textView respondsToSelector: @selector(updateForTextChange)])
{
[textView updateForTextChange];
}
}
答案 18 :(得分:6)
这个帖子有很多答案,但这是我喜欢的版本。
扩展现有的UITextView
类,因此可以轻松重复使用,并且不会拦截像textViewDidChange
这样的事件(可能会破坏)用户的代码,如果他们已经在其他地方拦截了这些事件。)
使用我的代码(如下所示),您可以轻松地将占位符添加到您的任何UITextViews
中:
self.textViewComments.placeholder = @"(Enter some comments here.)";
设置此新占位符值后,它会在UILabel
之上悄悄添加UITextView
,然后根据需要隐藏/显示:
好的,要进行这些更改,请添加包含此代码的“UITextViewHelper.h”文件:
// 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
...以及包含此内容的UITextViewHelper.m文件:
// 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
是的,这是很多代码,但是一旦你将它添加到你的项目并包含.h文件......
#import "UITextViewHelper.h"
...您可以在UITextViews
中轻松使用占位符。
虽然有一个问题。
如果你这样做:
self.textViewComments.placeholder = @"(Enter some comments here.)";
self.textViewComments.text = @"Ooooh, hello there";
...占位符将在文本的顶部显示。当您设置text
值时,不会调用任何常规通知,因此我无法确定如何调用我的函数来决定是否显示/隐藏占位符。
解决方案是设置textValue
而不是text
:
self.textViewComments.placeholder = @"(Enter some comments here.)";
self.textViewComments.textValue = @"Ooooh, hello there";
或者,您可以设置text
值,然后调用checkIfNeedToDisplayPlaceholder
。
self.textViewComments.text = @"Ooooh, hello there";
[self.textViewComments checkIfNeedToDisplayPlaceholder];
我喜欢这样的解决方案,因为它们“填补了Apple提供给我们的东西之间的差距”,以及我们(作为开发人员)在我们的应用中实际需要的差距。您编写此代码一次,将其添加到“helper”.m / .h文件库中,随着时间的推移,SDK实际上开始变得不那么令人沮丧了。
(我写了一个类似的帮助器,为我的UITextViews添加了一个“清除”按钮,另一件令人讨厌的事情存在于UITextField
但不存在于UITextView
......)
答案 19 :(得分:6)
首先在.h文件中添加标签。
我在这里
UILabel * lbl;
然后在viewDidLoad下的.m中声明它
lbl = [[UILabel alloc] initWithFrame:CGRectMake(8.0, 0.0,250, 34.0)];
lbl.font=[UIFont systemFontOfSize:14.0];
[lbl setText:@"Write a message..."];
[lbl setBackgroundColor:[UIColor clearColor]];
[lbl setTextColor:[UIColor lightGrayColor]];
[textview addSubview:lbl];
textview是我的TextView。
现在宣布
-(void)textViewDidChange:(UITextView *)textView {
if (![textView hasText]){
lbl.hidden = NO;
}
else{
lbl.hidden = YES;
}
}
您的Textview占位符已准备就绪!
答案 20 :(得分:6)
我建议使用pod&#39; UITextView + Placeholder&#39;
pod 'UITextView+Placeholder'
代码
#import "UITextView+Placeholder.h"
////
UITextView *textView = [[UITextView alloc] init];
textView.placeholder = @"How are you?";
textView.placeholderColor = [UIColor lightGrayColor];
答案 21 :(得分:6)
我制作了自己的'UITextView'子类版本。我喜欢 Sam Soffes 使用通知的想法,但我不喜欢drawRect:overwrite。对我来说似乎有点矫枉过正。我想我做了一个非常干净的实施。
您可以查看我的子类here。还包括一个演示项目。
答案 22 :(得分:5)
在UITextView中无法创建占位符,但您可以通过此方式生成类似占位符的效果。
1.
或者您可以在textview中添加标签,就像
一样 - (void)viewDidLoad{
commentTxtView.text = @"Comment";
commentTxtView.textColor = [UIColor lightGrayColor];
commentTxtView.delegate = self;
}
- (BOOL) textViewShouldBeginEditing:(UITextView *)textView
{
commentTxtView.text = @"";
commentTxtView.textColor = [UIColor blackColor];
return YES;
}
-(void) textViewDidChange:(UITextView *)textView
{
if(commentTxtView.text.length == 0){
commentTxtView.textColor = [UIColor lightGrayColor];
commentTxtView.text = @"Comment";
[commentTxtView resignFirstResponder];
}
}
并设置
lbl = [[UILabel alloc] initWithFrame:CGRectMake(10.0, 0.0,textView.frame.size.width - 10.0, 34.0)];
[lbl setText:kDescriptionPlaceholder];
[lbl setBackgroundColor:[UIColor clearColor]];
[lbl setTextColor:[UIColor lightGrayColor]];
textView.delegate = self;
[textView addSubview:lbl];
答案 23 :(得分:5)
这完全模仿了UITextField的占位符,其中占位符文本保持不变,直到您实际输入内容为止。
private let placeholder = "Type here"
@IBOutlet weak var textView: UITextView! {
didSet {
textView.textColor = UIColor.lightGray
textView.text = placeholder
textView.selectedRange = NSRange(location: 0, length: 0)
}
}
extension ViewController: UITextViewDelegate {
func textViewDidChangeSelection(_ textView: UITextView) {
// Move cursor to beginning on first tap
if textView.text == placeholder {
textView.selectedRange = NSRange(location: 0, length: 0)
}
}
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if textView.text == placeholder && !text.isEmpty {
textView.text = nil
textView.textColor = UIColor.black
textView.selectedRange = NSRange(location: 0, length: 0)
}
return true
}
func textViewDidChange(_ textView: UITextView) {
if textView.text.isEmpty {
textView.textColor = UIColor.lightGray
textView.text = placeholder
}
}
}
答案 24 :(得分:5)
- (void)textViewDidChange:(UITextView *)textView
{
placeholderLabel.hidden = YES;
}
在textview上添加标签。
答案 25 :(得分:4)
让我们轻松一点
创建一个UILabel并将其放在文本视图中(将文本设置为占位符 - 设置颜色为灰色 - 您可以在xib中执行所有操作) 现在在你的头文件中声明了UILabel以及textviewDelegate 现在,您可以在单击文本视图时隐藏标签
以下完整代码
头
@interface ViewController :UIViewController<UITextViewDelegate>{
}
@property (nonatomic,strong) IBOutlet UILabel *PlceHolder_label;
@property (nonatomic,strong) IBOutlet UITextView *TextView;
@end
实施
@implementation UploadFoodImageViewController
@synthesize PlceHolder_label,TextView;
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{
if([textView isEqual:TextView]){
[PlceHolder_label setHidden:YES];
[self.tabScrlVw setContentOffset:CGPointMake(0,150) animated:YES];
}
return YES;
}
@end
别忘了将textView和UILabel连接到xib的文件所有者
答案 26 :(得分:4)
这是另一种方法,它可以再现UITextField
占位符的轻微缩进:
将UITextField
拖到UITextView
下方,使其左上角对齐。将占位符文本添加到文本字段。
在viewDidLoad中,添加:
[tView setDelegate:self];
tView.contentInset = UIEdgeInsetsMake(-8,-8,0,0);
tView.backgroundColor = [UIColor clearColor];
然后添加:
- (void)textViewDidChange:(UITextView *)textView {
if (textView.text.length == 0) {
textView.backgroundColor = [UIColor clearColor];
} else {
textView.backgroundColor = [UIColor whiteColor];
}
}
答案 27 :(得分:4)
这是UITextView的一个方便的子类,它支持与UITextField类似的占位符。主要特点:
答案 28 :(得分:4)
我在swift写了一个类。您可以在需要时导入此类。
import UIKit
公共类CustomTextView:UITextView {
private struct Constants {
static let defaultiOSPlaceholderColor = UIColor(red: 0.0, green: 0.0, blue: 0.0980392, alpha: 0.22)
}
private let placeholderLabel: UILabel = UILabel()
private var placeholderLabelConstraints = [NSLayoutConstraint]()
@IBInspectable public var placeholder: String = "" {
didSet {
placeholderLabel.text = placeholder
}
}
@IBInspectable public var placeholderColor: UIColor = CustomTextView.Constants.defaultiOSPlaceholderColor {
didSet {
placeholderLabel.textColor = placeholderColor
}
}
override public var font: UIFont! {
didSet {
placeholderLabel.font = font
}
}
override public var textAlignment: NSTextAlignment {
didSet {
placeholderLabel.textAlignment = textAlignment
}
}
override public var text: String! {
didSet {
textDidChange()
}
}
override public var attributedText: NSAttributedString! {
didSet {
textDidChange()
}
}
override public var textContainerInset: UIEdgeInsets {
didSet {
updateConstraintsForPlaceholderLabel()
}
}
override public init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
commonInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
NSNotificationCenter.defaultCenter().addObserver(self,
selector: #selector(textDidChange),
name: UITextViewTextDidChangeNotification,
object: nil)
placeholderLabel.font = font
placeholderLabel.textColor = placeholderColor
placeholderLabel.textAlignment = textAlignment
placeholderLabel.text = placeholder
placeholderLabel.numberOfLines = 0
placeholderLabel.backgroundColor = UIColor.clearColor()
placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
addSubview(placeholderLabel)
updateConstraintsForPlaceholderLabel()
}
private func updateConstraintsForPlaceholderLabel() {
var newConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|-(\(textContainerInset.left + textContainer.lineFragmentPadding))-[placeholder]",
options: [],
metrics: nil,
views: ["placeholder": placeholderLabel])
newConstraints += NSLayoutConstraint.constraintsWithVisualFormat("V:|-(\(textContainerInset.top))-[placeholder]",
options: [],
metrics: nil,
views: ["placeholder": placeholderLabel])
newConstraints.append(NSLayoutConstraint(
item: placeholderLabel,
attribute: .Width,
relatedBy: .Equal,
toItem: self,
attribute: .Width,
multiplier: 1.0,
constant: -(textContainerInset.left + textContainerInset.right + textContainer.lineFragmentPadding * 2.0)
))
removeConstraints(placeholderLabelConstraints)
addConstraints(newConstraints)
placeholderLabelConstraints = newConstraints
}
@objc private func textDidChange() {
placeholderLabel.hidden = !text.isEmpty
}
public override func layoutSubviews() {
super.layoutSubviews()
placeholderLabel.preferredMaxLayoutWidth = textContainer.size.width - textContainer.lineFragmentPadding * 2.0
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self,
name: UITextViewTextDidChangeNotification,
object: nil)
}
}
答案 29 :(得分:4)
我仔细阅读了所有这些内容,但提出了一个非常简短的Swift 3解决方案,该解决方案适用于我的所有测试。它可以更具一般性,但过程很简单。这是我称之为“TextViewWithPlaceholder”的全部内容。
import UIKit
class TextViewWithPlaceholder: UITextView {
public var placeholder: String?
public var placeholderColor = UIColor.lightGray
private var placeholderLabel: UILabel?
// Set up notification listener when created from a XIB or storyboard.
// You can also set up init() functions if you plan on creating
// these programmatically.
override func awakeFromNib() {
super.awakeFromNib()
NotificationCenter.default.addObserver(self,
selector: #selector(TextViewWithPlaceholder.textDidChangeHandler(notification:)),
name: .UITextViewTextDidChange,
object: self)
placeholderLabel = UILabel()
placeholderLabel?.alpha = 0.85
placeholderLabel?.textColor = placeholderColor
}
// By using layoutSubviews, you can size and position the placeholder
// more accurately. I chose to hard-code the size of the placeholder
// but you can combine this with other techniques shown in previous replies.
override func layoutSubviews() {
super.layoutSubviews()
placeholderLabel?.textColor = placeholderColor
placeholderLabel?.text = placeholder
placeholderLabel?.frame = CGRect(x: 6, y: 4, width: self.bounds.size.width-16, height: 24)
if text.isEmpty {
addSubview(placeholderLabel!)
bringSubview(toFront: placeholderLabel!)
} else {
placeholderLabel?.removeFromSuperview()
}
}
// Whenever the text changes, just trigger a new layout pass.
func textDidChangeHandler(notification: Notification) {
layoutSubviews()
}
}
答案 30 :(得分:3)
我知道这个问题已经有了很多答案,但我并没有真正发现它们中的任何一个(至少在Swift中)。我需要UITextField
中UITextView
的“占位符”功能(我想要确切的行为,包括文本显示属性,动画等,并且不希望随着时间的推移而保持这种状态) 。我还想要一个提供与UITextField
完全相同的边界的解决方案(不是一个看似现在看起来有点类似的近似,但看起来与它完全一样并且看起来总是如此)。因此,虽然我最初并不喜欢将一个额外的控制干扰到混音中,但为了达到我的目标,似乎我必须使用实际的UITextField
并让它完成工作。
此解决方案处理占位符的定位并保持两个控件之间的字体同步,以便占位符文本是输入到控件中的文本的精确字体和位置(许多其他解决方案无法解决的问题)。
// This class is necessary to support "inset" (required to position placeholder
// appropriately in TextView)
//
class TextField: UITextField
{
var inset: UIEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0);
override func textRectForBounds(bounds: CGRect) -> CGRect
{
return UIEdgeInsetsInsetRect(bounds, inset);
}
override func placeholderRectForBounds(bounds: CGRect) -> CGRect
{
return UIEdgeInsetsInsetRect(bounds, inset);
}
}
// This class implements a UITextView that has a UITextField behind it, where the
// UITextField provides the border and the placeholder text functionality (so that the
// TextView looks and works like a UITextField).
//
class TextView : UITextView, UITextViewDelegate
{
var textField = TextField();
required init?(coder: NSCoder)
{
super.init(coder: coder);
}
override init(frame: CGRect, textContainer: NSTextContainer?)
{
super.init(frame: frame, textContainer: textContainer);
self.delegate = self;
// Create a background TextField with clear (invisible) text and disabled
self.textField.borderStyle = UITextBorderStyle.RoundedRect;
self.textField.textColor = UIColor.clearColor();
self.textField.userInteractionEnabled = false;
// Align the background TextView to where text appears in the TextField, so
// that any placeholder will be in the correct position.
self.textField.contentVerticalAlignment = UIControlContentVerticalAlignment.Top;
self.textField.inset = UIEdgeInsets(
top: self.textContainerInset.top,
left: self.textContainerInset.left + self.textContainer.lineFragmentPadding,
bottom: self.textContainerInset.bottom,
right: self.textContainerInset.right
);
// The background TextField should use the same font (for the placeholder)
self.textField.font = self.font;
self.addSubview(textField);
self.sendSubviewToBack(textField);
}
convenience init()
{
self.init(frame: CGRectZero, textContainer: nil)
}
override var font: UIFont?
{
didSet
{
// Keep the font of the TextView and background textField in sync
self.textField.font = self.font;
}
}
var placeholder: String? = nil
{
didSet
{
self.textField.placeholder = self.placeholder;
}
}
override func layoutSubviews()
{
super.layoutSubviews()
// Do not scroll the background textView
self.textField.frame = CGRectMake(0, self.contentOffset.y, self.frame.width, self.frame.height);
}
// UITextViewDelegate - Note: If you replace delegate, your delegate must call this
func scrollViewDidScroll(scrollView: UIScrollView)
{
// Do not scroll the background textView
self.textField.frame = CGRectMake(0, self.contentOffset.y, self.frame.width, self.frame.height);
}
// UITextViewDelegate - Note: If you replace delegate, your delegate must call this
func textViewDidChange(textView: UITextView)
{
// Updating the text in the background textView will cause the placeholder to
// appear/disappear (including any animations of that behavior - since the
// textView is doing this itself).
self.textField.text = self.text;
}
}
答案 31 :(得分:3)
我创建了一个快速3版highest ranked answer
您只需要对UITextView进行子类化。
import UIKit
class UIPlaceHolderTextView: UITextView {
//MARK: - Properties
@IBInspectable var placeholder: String?
@IBInspectable var placeholderColor: UIColor?
var placeholderLabel: UILabel?
//MARK: - Initializers
override func awakeFromNib() {
super.awakeFromNib()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
// Use Interface Builder User Defined Runtime Attributes to set
// placeholder and placeholderColor in Interface Builder.
if self.placeholder == nil {
self.placeholder = ""
}
if self.placeholderColor == nil {
self.placeholderColor = UIColor.black
}
NotificationCenter.default.addObserver(self, selector: #selector(textChanged(_:)), name: NSNotification.Name.UITextViewTextDidChange, object: nil)
}
func textChanged(_ notification: Notification) -> Void {
if self.placeholder?.count == 0 {
return
}
UIView.animate(withDuration: 0.25) {
if self.text.count == 0 {
self.viewWithTag(999)?.alpha = 1
}
else {
self.viewWithTag(999)?.alpha = 0
}
}
}
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
super.draw(rect)
if (self.placeholder?.count ?? 0) > 0 {
if placeholderLabel == nil {
placeholderLabel = UILabel.init()
placeholderLabel?.lineBreakMode = .byWordWrapping
placeholderLabel?.numberOfLines = 0
placeholderLabel?.font = self.font
placeholderLabel?.backgroundColor = self.backgroundColor
placeholderLabel?.textColor = self.placeholderColor
placeholderLabel?.alpha = 0
placeholderLabel?.tag = 999
self.addSubview(placeholderLabel!)
placeholderLabel?.translatesAutoresizingMaskIntoConstraints = false
placeholderLabel?.topAnchor.constraint(equalTo: self.topAnchor, constant: 7).isActive = true
placeholderLabel?.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 4).isActive = true
placeholderLabel?.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
placeholderLabel?.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
}
placeholderLabel?.text = self.placeholder
placeholderLabel?.sizeToFit()
self.sendSubview(toBack: self.placeholderLabel!)
}
if self.text.count == 0 && (self.placeholder?.count ?? 0) > 0 {
self.viewWithTag(999)?.alpha = 1
}
}
}
答案 32 :(得分:3)
我创建了一个实例变量来检查我是否会显示占位符:
BOOL showPlaceHolder;
UITextView * textView; // and also the textView
在viewDidLoad上我设置:
[self setPlaceHolder];
这就是它的作用:
- (void)setPlaceholder
{
textView.text = NSLocalizedString(@"Type your question here", @"placeholder");
textView.textColor = [UIColor lightGrayColor];
self.showPlaceHolder = YES; //we save the state so it won't disappear in case you want to re-edit it
}
我还创建了一个按钮来重新设置键盘。您不必这样做,但这里很酷的是,如果没有输入任何内容,则会再次显示占位符
- (void)textViewDidBeginEditing:(UITextView *)txtView
{
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(resignKeyboard)];
if (self.showPlaceHolder == YES)
{
textView.textColor = [UIColor blackColor];
textView.text = @"";
self.showPlaceHolder = NO;
}
}
- (void)resignKeyboard
{
[textView resignFirstResponder];
//here if you created a button like I did to resign the keyboard, you should hide it
if (textView.text.length == 0) {
[self setPlaceholder];
}
}
答案 33 :(得分:3)
How to insert placeholder in UITextView?
PJR的答案就像一个魅力。这里的那些对我不起作用。也许是iOS5的东西。
答案 34 :(得分:3)
好的,我的ansewer有点不同 我创建了一个小班,为你做。
TextViewShader.m文件
#import "TextViewShader.h"
@implementation TextViewShader
-(id)initWithShadedTextView:(NSString *)text textViewToShade:(UITextView *)textview {
self = [super initWithFrame:textview.frame];
if (self) {
if (shadeLabel==nil)
{
shadeLabel= [[UILabel alloc]initWithFrame:CGRectMake(10, 0, textview.frame.size.width, 30)];
}
shadeLabel.text =text;// @"Enter Your Support Request";
shadeLabel.textColor = [UIColor lightGrayColor];
[textview setDelegate: self];
[textview addSubview:shadeLabel];
}
return self;
}
-(void)textViewDidChange:(UITextView *)textView{
if (textView.text.length==0)
{
shadeLabel.hidden=false;
}
else
{
shadeLabel.hidden=true;
}
}
@end
TextViewShader.h文件
#import <UIKit/UIKit.h>
@interface TextViewShader : UIView<UITextViewDelegate>{
UILabel *shadeLabel;
}
-(id)initWithShadedTextView:(NSString *)text textViewToShade:(UITextView *)textview ;
@end
这是一行简单的代码用法(别忘了添加#import“TextViewShader.h”)
TextViewShader* shader = [[TextViewShader alloc]initWithShadedTextView:@"Enter Your Support Request" textViewToShade: youruitextviewToshade];
玩得开心:)
答案 35 :(得分:2)
一个常见的抱怨是iOS不为textview提供原生占位符功能。下面的UITextView
扩展程序试图通过提供本机功能所需的便利来解决这一问题,只需要一行代码就可以将占位符添加到textview实例。
这个解决方案的缺点是,因为菊花链委托调用,它很容易在iOS更新中(不太可能)更改UITextViewDelegate协议。具体来说,如果iOS添加了新的协议方法,并且您在委托中为带有占位符的文本视图实现了这些方法,那么除非您还更新了扩展以转发这些方法,否则不会调用这些方法调用。
或者,Inline Placeholder 答案是坚如磐石的,尽可能简单。
用法示例:
•如果获得占位符的文本视图不使用UITextViewDelegate
:
/* Swift 3 */
class NoteViewController : UIViewController {
@IBOutlet weak var noteView: UITextView!
override func viewDidLoad() {
noteView.addPlaceholder("Enter some text...", color: UIColor.lightGray)
}
}
- 或 -
•如果获得占位符的文本视图使用UITextViewDelegate
:
/* Swift 3 */
class NoteViewController : UIViewController, UITextViewDelegate {
@IBOutlet weak var noteView: UITextView!
override func viewDidLoad() {
noteView.addPlaceholder("Phone #", color: UIColor.lightGray, delegate: self)
}
}
实施(UITextView
延期):
/* Swift 3 */
extension UITextView: UITextViewDelegate
{
func addPlaceholder(_ placeholderText : String,
color : UIColor? = UIColor.lightGray,
delegate : UITextViewDelegate? = nil) {
self.delegate = self // Make receiving textview instance a delegate
let placeholder = UITextView() // Need delegate storage ULabel doesn't provide
placeholder.isUserInteractionEnabled = false //... so we *simulate* UILabel
self.addSubview(placeholder) // Add to text view instance's view tree
placeholder.sizeToFit() // Constrain to fit inside parent text view
placeholder.tintColor = UIColor.clear // Unused in textviews. Can host our 'tag'
placeholder.frame.origin = CGPoint(x: 5, y: 0) // Don't cover I-beam cursor
placeholder.delegate = delegate // Use as cache for caller's delegate
placeholder.font = UIFont.italicSystemFont(ofSize: (self.font?.pointSize)!)
placeholder.text = placeholderText
placeholder.textColor = color
}
func findPlaceholder() -> UITextView? { // find placeholder by its tag
for subview in self.subviews {
if let textview = subview as? UITextView {
if textview.tintColor == UIColor.clear { // sneaky tagging scheme
return textview
}
}
}
return nil
}
/*
* Safely daisychain to caller delegate methods as appropriate...
*/
public func textViewDidChange(_ textView: UITextView) { // ← need this delegate method
if let placeholder = findPlaceholder() {
placeholder.isHidden = !self.text.isEmpty // ← ... to do this
placeholder.delegate?.textViewDidChange?(textView)
}
}
/*
* Since we're becoming a delegate on behalf of this placeholder-enabled
* text view instance, we must forward *all* that protocol's activity expected
* by the instance, not just the particular optional protocol method we need to
* intercept, above.
*/
public func textViewDidEndEditing(_ textView: UITextView) {
if let placeholder = findPlaceholder() {
placeholder.delegate?.textViewDidEndEditing?(textView)
}
}
public func textViewDidBeginEditing(_ textView: UITextView) {
if let placeholder = findPlaceholder() {
placeholder.delegate?.textViewDidBeginEditing?(textView)
}
}
public func textViewDidChangeSelection(_ textView: UITextView) {
if let placeholder = findPlaceholder() {
placeholder.delegate?.textViewDidChangeSelection?(textView)
}
}
public func textViewShouldEndEditing(_ textView: UITextView) -> Bool {
if let placeholder = findPlaceholder() {
guard let retval = placeholder.delegate?.textViewShouldEndEditing?(textView) else {
return true
}
return retval
}
return true
}
public func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
if let placeholder = findPlaceholder() {
guard let retval = placeholder.delegate?.textViewShouldBeginEditing?(textView) else {
return true
}
return retval
}
return true
}
public func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if let placeholder = findPlaceholder() {
guard let retval = placeholder.delegate?.textView?(textView, shouldChangeTextIn: range, replacementText: text) else {
return true
}
return retval
}
return true
}
public func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
if let placeholder = findPlaceholder() {
guard let retval = placeholder.delegate?.textView?(textView, shouldInteractWith: URL, in: characterRange, interaction:
interaction) else {
return true
}
return retval
}
return true
}
public func textView(_ textView: UITextView, shouldInteractWith textAttachment: NSTextAttachment, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
if let placeholder = findPlaceholder() {
guard let retval = placeholder.delegate?.textView?(textView, shouldInteractWith: textAttachment, in: characterRange, interaction: interaction) else {
return true
}
return retval
}
return true
}
}
1。 作为UITextView等重要iOS类的扩展,重要的是要知道此代码与任何textviews都有无交互不会激活占位符,例如尚未通过调用 addPlaceholder()
2。 支持占位符的文字视图透明地变为 UITextViewDelegate
,以跟踪字符数,以控制占位符的可见性。如果将代理传递给 addPlaceholder()
,则此代码以菊花链形式(即转发)将回调委托给该代理。
3。 作者正在研究检查 UITextViewDelegate
协议并代理协议的方法自动而不必对每种方法进行硬编码。这将接收来自方法签名更改和添加到协议的新方法的代码。
答案 36 :(得分:2)
这是一种简单而聪明的方法来获得完美的行为。
让我们从UITextField
借用占位符。
设置textField并将其文本设置为透明。
self.placeholderTextField = [[UITextField alloc] init];
/* adjust the frame to fit it in the first line of your textView */
self.placeholderTextField.frame = CGRectMake(0.0, 0.0, yourTextView.width, 30.0);
self.placeholderTextField.textColor = [UIColor clearColor];
self.placeholderTextField.userInteractionEnabled = NO;
self.placeholderTextField.font = yourTextView.font;
self.placeholderTextField.placeholder = @"sample placeholder";
[yourTextView addSubview:self.placeholderTextField];
设置textView的委托并同步textField和textView。
yourTextView.delegate = self;
然后
- (void)textViewDidChange:(UITextView *)textView {
self.placeholderTextField.text = textView.text;
}
答案 37 :(得分:2)
更简单的方法是创建一个辅助UITextView,它具有与原始文本视图相同的所有属性,但不同的textColor除外,它们具有约束以确保它们保持对齐。然后,当在主文本视图中输入任何字符时,隐藏克隆的文本视图,否则显示带有一些文本的克隆文本视图。
这可以通过多种方式实现,但是相对干净的方法是将UITextView子类化并将所有这些逻辑保留在子类中。
所以,子类UITextView并允许它懒洋洋地创建它的占位符视图:
接口文件:
@interface FOOTextView : UITextView <UITextViewDelegate>
@property (nonatomic, copy) NSString *placeholderText;
- (void)checkPlaceholder;
@end
实施档案:
#import "FOOTextView.h"
@interface FOOTextView ()
@property (nonatomic, strong) UITextView *placeholderTextView;
@end
@implementation FOOTextView
- (void)checkPlaceholder {
// Hide the placeholder text view if we've got any text
self.placeholderTextView.hidden = (self.text.length > 0 || self.attributedText.length > 0);
}
- (void)setPlaceholderText:(NSString *)placeholderText {
_placeholderText = [placeholderText copy];
// Setup the placeholder text view if we haven't already
[self setupPlaceholderTextView];
// Apply the placeholder text to the placeholder text view
self.placeholderTextView.text = placeholderText;
}
- (void)setupPlaceholderTextView {
if (!self.placeholderTextView) {
// Setup the place holder text view, duplicating our visual setup
self.placeholderTextView = [[UITextView alloc] initWithFrame:CGRectZero];
self.placeholderTextView.translatesAutoresizingMaskIntoConstraints = NO;
self.placeholderTextView.textColor = self.placeholderTextColor ? self.placeholderTextColor : [UIColor colorWithRed:199.f/255.f green:199.f/255.f blue:205.f/255.f alpha:1.f];
self.placeholderTextView.userInteractionEnabled = NO;
self.placeholderTextView.font = self.font;
self.placeholderTextView.textAlignment = self.textAlignment;
self.placeholderTextView.backgroundColor = self.backgroundColor;
self.placeholderTextView.editable = NO;
// Our background color must be clear for the placeholder text view to show through
self.backgroundColor = [UIColor clearColor];
// Insert the placeholder text view into our superview, below ourself so it shows through
[self.superview insertSubview:self.placeholderTextView belowSubview:self];
// Setup constraints to ensure the placeholder text view stays aligned with us
NSLayoutConstraint *constraintCenterX = [NSLayoutConstraint constraintWithItem:self.placeholderTextView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterX multiplier:1.f constant:0.f];
NSLayoutConstraint *constraintCenterY = [NSLayoutConstraint constraintWithItem:self.placeholderTextView attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterY multiplier:1.f constant:0.f];
NSLayoutConstraint *constraintWidth = [NSLayoutConstraint constraintWithItem:self.placeholderTextView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeWidth multiplier:1.f constant:0.f];
NSLayoutConstraint *constraintHeight = [NSLayoutConstraint constraintWithItem:self.placeholderTextView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeHeight multiplier:1.f constant:0.f];
NSArray *constraints = @[constraintCenterX, constraintCenterY, constraintWidth, constraintHeight];
[self.superview addConstraints:constraints];
}
}
- (void)setPlaceholderTextColor:(UIColor *)placeholderTextColor {
_placeholderTextColor = placeholderTextColor;
self.placeholderTextView.textColor = _placeholderTextColor;
}
- (void)setBackgroundColor:(UIColor *)backgroundColor {
// We don't want a background color ourselves, instead we want our placeholder text view to have the desired background color
[self.placeholderTextView setBackgroundColor:backgroundColor];
}
- (void)removeFromSuperview {
// Ensure we also remove our placeholder text view
[self.placeholderTextView removeFromSuperview];
self.placeholderTextView = nil;
[super removeFromSuperview];
}
#pragma mark - Text View Delegation
- (void)textViewDidChange:(UITextView *)textView {
[self checkPlaceholder];
}
@end
使用上面的类,如果你将FOOTextView的委托实例设置为自己,那么一切都将开箱即用:
FOOTextView *myTextView = ...
myTextView.placeholderText = @"What's on your mind?";
myTextView.placeholderTextColor = [UIColor lightGrayColor];
myTextView.delegate = myTextView;
如果您希望另一个对象接管作为委托,那么您只需要在textViewDidChange:委托方法中调用文本视图的checkPlaceholder方法,例如;
FOOTextView *myTextView = ...
myTextView.placeholderText = @"What's on your mind?";
myTextView.placeholderTextColor = [UIColor lightGrayColor];
myTextView.delegate = self;
self.myTextView = myTextView;
- (void)textViewDidChange:(UITextView *)textView {
// Call the checkPlaceholder method to update the visuals
[self.myTextView checkPlaceholder];
}
答案 38 :(得分:2)
- (void)viewDidLoad {
[super viewDidLoad];
self.textViewEmpty = YES;
// Text view
self.textView = [[UITextView alloc] init];
self.textView.translatesAutoresizingMaskIntoConstraints = NO; // For AutoLayout
self.textView.delegate = self;
self.textView.textColor = [UIColor grayColor];
self.textView.text = @"Placeholder";
// Add subview and constraints
}
#pragma mark - UITextView
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView {
if (self.isTextViewEmpty) {
textView.textColor = [UIColor blackColor];
textView.text = @"";
}
return YES;
}
- (void)textViewDidChange:(UITextView *)textView {
if (textView.text.length > 0) {
self.textViewEmpty = NO;
} else {
self.textViewEmpty = YES;
}
}
- (BOOL)textViewShouldEndEditing:(UITextView *)textView {
if (self.isTextViewEmpty) {
textView.textColor = [UIColor lightGrayColor];
textView.text = placeholderText;
}
return YES;
}
答案 39 :(得分:2)
在.h班级
@interface RateCommentViewController : UIViewController<UITextViewDelegate>{IBoutlet UITextview *commentTxtView;}
在.m班
- (void)viewDidLoad{
commentTxtView.text = @"Comment";
commentTxtView.textColor = [UIColor lightGrayColor];
commentTxtView.delegate = self;
}
- (BOOL) textViewShouldBeginEditing:(UITextView *)textView
{
commentTxtView.text = @"";
commentTxtView.textColor = [UIColor blackColor];
return YES;
}
-(void) textViewDidChange:(UITextView *)textView
{
if(commentTxtView.text.length == 0){
commentTxtView.textColor = [UIColor lightGrayColor];
commentTxtView.text = @"Comment";
[commentTxtView resignFirstResponder];
}
}
答案 40 :(得分:2)
另一种解决方案
import UIKit
protocol PlaceholderTextViewDelegate: class {
func placeholderTextViewDidChangeText(_ text: String)
func placeholderTextViewDidEndEditing(_ text: String)
}
final class PlaceholderTextView: UITextView {
weak var notifier: PlaceholderTextViewDelegate?
var ignoreEnterAction: Bool = true
var placeholder: String? {
didSet {
text = placeholder
selectedRange = NSRange(location: 0, length: 0)
}
}
var placeholderColor = UIColor.lightGray {
didSet {
if text == placeholder {
textColor = placeholderColor
}
}
}
var normalTextColor = UIColor.lightGray
var placeholderFont = UIFont.sfProRegular(28)
fileprivate var placeholderLabel: UILabel?
// MARK: - LifeCycle
override var text: String? {
didSet {
if text == placeholder {
textColor = placeholderColor
} else {
textColor = normalTextColor
}
}
}
init() {
super.init(frame: CGRect.zero, textContainer: nil)
awakeFromNib()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func awakeFromNib() {
super.awakeFromNib()
self.delegate = self
}
}
extension PlaceholderTextView: UITextViewDelegate {
// MARK: - UITextViewDelegate
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if text == "" && textView.text == placeholder {
return false
}
if let placeholder = placeholder,
textView.text == placeholder,
range.location <= placeholder.count {
textView.text = ""
}
if ignoreEnterAction && text == "\n" {
textView.resignFirstResponder()
return false
}
return true
}
func textViewDidChange(_ textView: UITextView) {
if let placeholder = placeholder {
textView.text = textView.text.replacingOccurrences(of: placeholder, with: "")
}
if let placeholder = placeholder,
text?.isEmpty == true {
text = placeholder
textColor = placeholderColor
selectedRange = NSRange(location: 0, length: 0)
} else {
textColor = normalTextColor
}
notifier?.placeholderTextViewDidChangeText(textView.text)
}
func textViewDidChangeSelection(_ textView: UITextView) {
if let placeholder = placeholder,
text == placeholder {
selectedRange = NSRange(location: 0, length: 0)
}
}
func textViewDidEndEditing(_ textView: UITextView) {
notifier?.placeholderTextViewDidEndEditing(textView.text)
if let placeholder = placeholder,
text?.isEmpty == true {
text = placeholder
textColor = placeholderColor
selectedRange = NSRange(location: 0, length: 0)
} else {
textColor = normalTextColor
}
}
}
结果:
答案 41 :(得分:2)
- (BOOL) textViewShouldBeginEditing:(UITextView *)textView
{
//NSLog(@"textViewShouldBeginEditing");
if( [tvComment.text isEqualToString:@"Comment"] && [tvComment.textColor isEqual:[UIColor lightGrayColor]] ){
tvComment.text = @"";
tvComment.textColor = [UIColor blackColor];
}
return YES;
}
- (void)keyboardWillBeHidden:(NSNotification*)aNotification{
//NSLog(@"keyboardWillBeHidden");
//Manage comment field placeholdertext
if(tvComment.text.length == 0){
tvComment.textColor = [UIColor lightGrayColor];
tvComment.text = @"Comment";
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
tvComment.textColor = [UIColor lightGrayColor];
}
TVComment是保存有问题的textView的属性。这样就可以了。
答案 42 :(得分:2)
在尝试了一些提议的方法和posted it to Github后,我写了一个更清晰的实现。欢迎提出请求和问题。
与此处介绍的其他方法相比,有一些重要的改进:
drawRect:
内分配UILabel。 (请不要那样做。)UITextField
)。答案 43 :(得分:1)
使用CATextLayer.
将CATextLayer
添加到UITextView's
层。
使用UITextViewDelegate
方法,只需更改CATextLayer
的颜色即可。
func txtViewPlaceholder() {
let textlayer = CATextLayer()
textlayer.frame = CGRect(x: 5, y: 5, width: 200, height: 18)
textlayer.fontSize = 12
textlayer.alignmentMode = kCAAlignmentLeft
textlayer.string = "Enter here"
textlayer.isWrapped = true
textlayer.name = "placeholder"
textlayer.backgroundColor = UIColor.white.cgColor
textlayer.foregroundColor = UIColor.black.cgColor
yourTxtVw.layer.insertSublayer(textlayer, at: 0)
}
func removeAddPlaceholder(remove: Bool, textView: UITextView) {
for layers in textView.layer.sublayers! where layers.name == "placeholder" {
if remove {
(layers as! CATextLayer).foregroundColor = UIColor.white.cgColor
} else {
(layers as! CATextLayer).foregroundColor = UIColor.black.cgColor
}
}
}
extension YourViewController : UITextViewDelegate {
func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
removeAddPlaceholder(remove: true, textView: textView)
return true
}
func textViewDidEndEditing(_ textView: UITextView) {
if textView.text.count <= 0 {
removeAddPlaceholder(remove: false, textView: textView)
}
}
}
答案 44 :(得分:1)
这是swift 3.1的代码
Jason George的原始代码在第一个答案中。
不要忘记在界面构建器中将TextView的自定义类设置为UIPlaceHolderTextView,然后设置占位符和placeHolder属性。
import UIKit
@IBDesignable
class UIPlaceHolderTextView: UITextView {
@IBInspectable var placeholder: String = ""
@IBInspectable var placeholderColor: UIColor = UIColor.lightGray
private let uiPlaceholderTextChangedAnimationDuration: Double = 0.05
private let defaultTagValue = 999
private var placeHolderLabel: UILabel?
override func awakeFromNib() {
super.awakeFromNib()
NotificationCenter.default.addObserver(
self,
selector: #selector(textChanged),
name: NSNotification.Name.UITextViewTextDidChange,
object: nil
)
}
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
NotificationCenter.default.addObserver(
self,
selector: #selector(textChanged),
name: NSNotification.Name.UITextViewTextDidChange,
object: nil
)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
NotificationCenter.default.addObserver(
self,
selector: #selector(textChanged),
name: NSNotification.Name.UITextViewTextDidChange,
object: nil
)
}
deinit {
NotificationCenter.default.removeObserver(
self,
name: NSNotification.Name.UITextViewTextDidChange,
object: nil
)
}
@objc private func textChanged() {
guard !placeholder.isEmpty else {
return
}
UIView.animate(withDuration: uiPlaceholderTextChangedAnimationDuration) {
if self.text.isEmpty {
self.viewWithTag(self.defaultTagValue)?.alpha = CGFloat(1.0)
}
else {
self.viewWithTag(self.defaultTagValue)?.alpha = CGFloat(0.0)
}
}
}
override var text: String! {
didSet{
super.text = text
textChanged()
}
}
override func draw(_ rect: CGRect) {
if !placeholder.isEmpty {
if placeHolderLabel == nil {
placeHolderLabel = UILabel.init(frame: CGRect(x: 0, y: 8, width: bounds.size.width - 16, height: 0))
placeHolderLabel!.lineBreakMode = .byWordWrapping
placeHolderLabel!.numberOfLines = 0
placeHolderLabel!.font = font
placeHolderLabel!.backgroundColor = UIColor.clear
placeHolderLabel!.textColor = placeholderColor
placeHolderLabel!.alpha = 0
placeHolderLabel!.tag = defaultTagValue
self.addSubview(placeHolderLabel!)
}
placeHolderLabel!.text = placeholder
placeHolderLabel!.sizeToFit()
self.sendSubview(toBack: placeHolderLabel!)
if text.isEmpty && !placeholder.isEmpty {
viewWithTag(defaultTagValue)?.alpha = 1.0
}
}
super.draw(rect)
}
}
答案 45 :(得分:1)
我遵循了code from this link。只有7个简单步骤。当通过textView的textViewDidChangeSelection(_ textView: UITextView)
委托方法输入文本或从textView中删除文本时,它将UILabel添加到textView并隐藏/显示标签。我将步骤放在代码上方的注释中。
// 1. make sure to include the UITextViewDelegate
class YourClass: UITextViewDelegate {
@IBOutlet weak var textView : UITextView!
// 2. create placeholder textLabel
let placeHolderTextLabel: UILabel = {
let placeholderLabel = UILabel()
placeholderLabel.text = "Placeholder text..."
placeholderLabel.sizeToFit()
placeholderLabel.textColor = UIColor.lightGray
return placeholderLabel
}()
override func viewDidLoad() {
super.viewDidLoad()
// 3. set textView delegate
textView.delegate = self
configurePlaceholderTextLabel()
}
func configurePlaceholderTextLabel() {
// 4. add placeholder label to textView, set it's frame and font
textView.addSubview(placeHolderTextLabel)
placeHolderTextLabel.frame.origin = CGPoint(x: 5, y: (textView.font?.pointSize)! / 2)
placeHolderTextLabel.font = UIFont.systemFont(ofSize: (textView.font?.pointSize)!)
// 5. decide wether the placeHolderTextLabel is hidden or not depending on if there is or isn't text inside the textView
placeHolderTextLabel.isHidden = !textView.text.isEmpty
}
// 6. implement textView delegate method to update the placeHolderTextLabel when the text is changed
func textViewDidChangeSelection(_ textView: UITextView) {
// 7. decide wether the placeHolderTextLabel is hidden or not depending on if there is or isn't text inside the textView when text in textView is changed
placeHolderTextLabel.isHidden = !textView.text.isEmpty
}
}
答案 46 :(得分:1)
import UIKit
@IBDesignable
open class KMPlaceholderTextView: UITextView {
private struct Constants {
static let defaultiOSPlaceholderColor = UIColor(red: 0.0, green: 0.0, blue: 0.0980392, alpha: 0.22)
}
public let placeholderLabel: UILabel = UILabel()
private var placeholderLabelConstraints = [NSLayoutConstraint]()
@IBInspectable open var placeholder: String = "" {
didSet {
placeholderLabel.text = placeholder
}
}
@IBInspectable open var placeholderColor: UIColor = KMPlaceholderTextView.Constants.defaultiOSPlaceholderColor {
didSet {
placeholderLabel.textColor = placeholderColor
}
}
override open var font: UIFont! {
didSet {
if placeholderFont == nil {
placeholderLabel.font = font
}
}
}
open var placeholderFont: UIFont? {
didSet {
let font = (placeholderFont != nil) ? placeholderFont : self.font
placeholderLabel.font = font
}
}
override open var textAlignment: NSTextAlignment {
didSet {
placeholderLabel.textAlignment = textAlignment
}
}
override open var text: String! {
didSet {
textDidChange()
}
}
override open var attributedText: NSAttributedString! {
didSet {
textDidChange()
}
}
override open var textContainerInset: UIEdgeInsets {
didSet {
updateConstraintsForPlaceholderLabel()
}
}
override public init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
commonInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
#if swift(>=4.2)
let notificationName = UITextView.textDidChangeNotification
#else
let notificationName = NSNotification.Name.UITextView.textDidChangeNotification
#endif
NotificationCenter.default.addObserver(self,
selector: #selector(textDidChange),
name: notificationName,
object: nil)
placeholderLabel.font = font
placeholderLabel.textColor = placeholderColor
placeholderLabel.textAlignment = textAlignment
placeholderLabel.text = placeholder
placeholderLabel.numberOfLines = 0
placeholderLabel.backgroundColor = UIColor.clear
placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
addSubview(placeholderLabel)
updateConstraintsForPlaceholderLabel()
}
private func updateConstraintsForPlaceholderLabel() {
var newConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-(\(textContainerInset.left + textContainer.lineFragmentPadding))-[placeholder]",
options: [],
metrics: nil,
views: ["placeholder": placeholderLabel])
newConstraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|-(\(textContainerInset.top))-[placeholder]",
options: [],
metrics: nil,
views: ["placeholder": placeholderLabel])
newConstraints.append(NSLayoutConstraint(
item: placeholderLabel,
attribute: .width,
relatedBy: .equal,
toItem: self,
attribute: .width,
multiplier: 1.0,
constant: -(textContainerInset.left + textContainerInset.right + textContainer.lineFragmentPadding * 2.0)
))
removeConstraints(placeholderLabelConstraints)
addConstraints(newConstraints)
placeholderLabelConstraints = newConstraints
}
@objc private func textDidChange() {
placeholderLabel.isHidden = !text.isEmpty
self.layoutIfNeeded()
}
open override func layoutSubviews() {
super.layoutSubviews()
placeholderLabel.preferredMaxLayoutWidth = textContainer.size.width - textContainer.lineFragmentPadding * 2.0
}
deinit {
#if swift(>=4.2)
let notificationName = UITextView.textDidChangeNotification
#else
let notificationName = NSNotification.Name.UITextView.textDidChangeNotification
#endif
NotificationCenter.default.removeObserver(self,
name: notificationName,
object: nil)
}
}
答案 47 :(得分:1)
又一个答案:
https://github.com/gcamp/GCPlaceholderTextView
将IB中UITextView
的班级更改为GCPlaceholderTextView
并设置placeholder
属性
答案 48 :(得分:1)
如果您正在寻找一种简单的方法来实现这一目标,请尝试我的方法:
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
if ([[textView text] isEqualToString:PLACE_HOLDER_TEXT]) {
textView.text = @"";
textView.textColor = [UIColor blackColor];
}
return YES;
}
-(BOOL)textViewShouldEndEditing:(UITextView *)textView
{
if ([[textView text] length] == 0) {
textView.text = PLACE_HOLDER_TEXT;
textView.textColor = [UIColor lightGrayColor];
}
return YES;
}
是的,PLACE_HOLDER_TEXT
是包含占位符的NSString
答案 49 :(得分:1)
我找到了自己的解决方案
- (void)textViewDidBeginEditing:(UITextView *)textView
{
if ([textView.text isEqualToString:PLACEHOLDER_TEXT])
{
textView.textColor = [UIColor lightGrayColor];
dispatch_async(dispatch_get_main_queue(), ^
{
textView.selectedRange = NSMakeRange(0, 0);
});
}
else
{
textView.textColor = [UIColor blackColor];
}
[textView becomeFirstResponder];
}
- (void)textViewDidEndEditing:(UITextView *)textView
{
if ([textView.text isEqualToString:@""])
{
textView.text = PLACEHOLDER_TEXT;
textView.textColor = [UIColor lightGrayColor];
}
[textView resignFirstResponder];
}
- (BOOL)textView:(UITextView *)textView
shouldChangeTextInRange:(NSRange)range
replacementText:(NSString *)text
{
if (range.location == 0 && range.length == [[textView text] length] && [text isEqualToString:@""])
{
textView.text = PLACEHOLDER_TEXT;
textView.textColor = [UIColor lightGrayColor];
dispatch_async(dispatch_get_main_queue(), ^
{
textView.selectedRange = NSMakeRange(0, 0);
});
return NO;
}
if ([textView.text isEqualToString:PLACEHOLDER_TEXT])
{
textView.text = @"";
textView.textColor = [UIColor blackColor];
}
return YES;
}
答案 50 :(得分:0)
答案 51 :(得分:0)
迅速5。正常工作。
class BaseTextView: UITextView {
// MARK: - Views
private var placeholderLabel: UIlabel!
// MARK: - Init
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
setupUI()
startupSetup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupUI()
startupSetup()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
// MARK: - Setup UI
private extension BaseTextView {
func setupUI() {
addPlaceholderLabel()
textColor = .textColor
}
func addPlaceholderLabel() {
placeholderLabel = BaseLabel(frame: .zero)
placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
insertSubview(placeholderLabel, at: 0)
placeholderLabel.alpha = 0
placeholderLabel.numberOfLines = 0
placeholderLabel.backgroundColor = .clear
placeholderLabel.textColor = .lightTextColor
placeholderLabel.lineBreakMode = .byWordWrapping
placeholderLabel.isUserInteractionEnabled = false
placeholderLabel.font = UIFont.openSansSemibold.withSize(12)
placeholderLabel.topAnchor.constraint(equalTo: topAnchor, constant: 8).isActive = true
placeholderLabel.leftAnchor.constraint(equalTo: leftAnchor, constant: 5).isActive = true
placeholderLabel.rightAnchor.constraint(lessThanOrEqualTo: rightAnchor, constant: -8).isActive = true
placeholderLabel.bottomAnchor.constraint(lessThanOrEqualTo: bottomAnchor, constant: -8).isActive = true
}
}
// MARK: - Startup
private extension BaseTextView {
func startupSetup() {
addObservers()
textChanged(nil)
font = UIFont.openSansSemibold.withSize(12)
}
func addObservers() {
NotificationCenter.default.addObserver(self, selector: #selector(textChanged(_:)), name: UITextView.textDidChangeNotification, object: nil)
}
}
// MARK: - Actions
private extension BaseTextView {
@objc func textChanged(_ sender: Notification?) {
UIView.animate(withDuration: 0.2) {
self.placeholderLabel.alpha = self.text.count == 0 ? 1 : 0
}
}
}
// MARK: - Public methods
extension BaseTextView {
public func setPlaceholder(_ placeholder: String) {
placeholderLabel.text = placeholder
}
}
答案 52 :(得分:0)
老实说,2019年。
最好的解决方案是:
在情节提要中添加一个完美的占位符。 (完全可以是您想要的任何位置,样式,动画,阴影。)
现在需要>>>一行代码<<<来打开和关闭占位符。
这不是问题。
这通常是错误的工程,试图对其进行概括(并且我们都对某些事物进行概括)。
事实是
今天,您的客户不可避免地需要一些非常自定义的占位符,这些占位符将不断更改样式和设计。
这是>>>的一行代码<<<,所以这不是问题。
询问如何“占位符”就像问“我有一个变量X,我想在其中添加五个”。
再简单不过了;不要努力。保持灵活性。
请注意,通过Apple控件,其中要做包含一个占位符-在100%的情况下,客户希望获得一些不同的东西,因此无论如何您都忽略了给定的占位符,并以任何方式简单地“创建了占位符”希望。
也请注意,在100%的真实世界项目中,当占位符出现和消失(淡入淡出,滑行等等)时,您的客户都会需要动画(或其他内容)。
class Example: UITextViewDelegate {
@IBOutlet var textInput: UITextView!
@IBOutlet var placeholder: .. whatever it is, image, animation, text, who knows
@IBOutlet var placeholderSlidey: NSLayoutConstraint!
var hidey: Bool = false {
didSet {
let t = hidey ? view.bounds.width : 0
let h = UIViewPropertyAnimator(
duration: 0.15, curve: .linear) { [weak self] in
self?.placeholderSlidey.constant = t
self?.view.layoutIfNeeded()
}
h.startAnimation()
}
}
func textViewDidChange(_ textView: UITextView) {
hidey = !textView.text.isEmpty
}
答案 53 :(得分:0)
基于这里已经提出的一些重要建议,我能够将UITextView
的以下轻量级,与Interface-Builder兼容的子类放在一起,
UITextField
。text
属性无关的外部类完全分开。欢迎提出任何改进建议,尤其是如果有任何方法可以通过编程方式拉动iOS的占位符颜色,而不是对其进行硬编码的话。
Swift v5:
import UIKit
@IBDesignable class TextViewWithPlaceholder: UITextView {
override var text: String! { // Ensures that the placeholder text is never returned as the field's text
get {
if showingPlaceholder {
return "" // When showing the placeholder, there's no real text to return
} else { return super.text }
}
set { super.text = newValue }
}
@IBInspectable var placeholderText: String = ""
@IBInspectable var placeholderTextColor: UIColor = UIColor(red: 0.78, green: 0.78, blue: 0.80, alpha: 1.0) // Standard iOS placeholder color (#C7C7CD). See https://stackoverflow.com/questions/31057746/whats-the-default-color-for-placeholder-text-in-uitextfield
private var showingPlaceholder: Bool = true // Keeps track of whether the field is currently showing a placeholder
override func didMoveToWindow() {
super.didMoveToWindow()
if text.isEmpty {
showPlaceholderText() // Load up the placeholder text when first appearing, but not if coming back to a view where text was already entered
}
}
override func becomeFirstResponder() -> Bool {
// If the current text is the placeholder, remove it
if showingPlaceholder {
text = nil
textColor = nil // Put the text back to the default, unmodified color
showingPlaceholder = false
}
return super.becomeFirstResponder()
}
override func resignFirstResponder() -> Bool {
// If there's no text, put the placeholder back
if text.isEmpty {
showPlaceholderText()
}
return super.resignFirstResponder()
}
private func showPlaceholderText() {
showingPlaceholder = true
textColor = placeholderTextColor
text = placeholderText
}
}
答案 54 :(得分:0)
这是我的带有占位符支持的UITextView版本。斯威夫特4.2 https://gist.github.com/hlung/c5dda3a0c2087e5ae6c1fce8822c4713
具有占位符文本支持的UITextView子类。它使用另一个 UILabel显示占位符,当文本为空时显示。
答案 55 :(得分:0)
Jason's answer看起来有些偏差,通过调整_placeHolderLabel的偏移来修复它:
- (void)drawRect:(CGRect)rect
{
if( [[self placeholder] length] > 0 )
{
if (_placeHolderLabel == nil )
{
if ([[UIDevice currentDevice].systemVersion floatValue] >= 7)
_placeHolderLabel = [[UILabel alloc] initWithFrame:CGRectMake(4,8,self.bounds.size.width - 8,0)];
else
_placeHolderLabel = [[UILabel alloc] initWithFrame:CGRectMake(8,8,self.bounds.size.width - 16,0)];
_placeHolderLabel.lineBreakMode = NSLineBreakByWordWrapping;
_placeHolderLabel.numberOfLines = 0;
_placeHolderLabel.font = self.font;
_placeHolderLabel.backgroundColor = [UIColor clearColor];
_placeHolderLabel.textColor = self.placeholderColor;
_placeHolderLabel.alpha = 0;
_placeHolderLabel.tag = 999;
[self addSubview:_placeHolderLabel];
}
_placeHolderLabel.text = self.placeholder;
[_placeHolderLabel sizeToFit];
[self sendSubviewToBack:_placeHolderLabel];
}
if( [[self text] length] == 0 && [[self placeholder] length] > 0 )
{
[[self viewWithTag:999] setAlpha:1];
}
[super drawRect:rect];
}
答案 56 :(得分:0)
更简单并仍然考虑用户在某个时刻输入的某些文字
BOOL placeHolderTextVisible;
在viewDidLoad上,将其设置为YES(或DidMoveToSuperview,或awakeFromNib)
然后,开启 - (BOOL)textView:(UITextView *)textView shouldBeginEditing
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView;
{
if (placeHolderTextVisible) {
placeHolderTextVisible = NO;
textView.text = @"";
}
return YES;
}
答案 57 :(得分:0)
Swift 3.1
在尝试了所有快速答案后,这个答案将为我节省3个小时的研究时间。希望这会有所帮助。
确保textField(无论您拥有的自定义名称)是否指向Storyboard中的委托,并且@IBOutlet位于yourCustomTextField
添加到viewDidLoad()
以下内容,加载视图时会显示:
告诉我看起来像占位符:
yourCustomTextField = "Start typing..."
yourCustomTextField.textColor = .lightGray
UIViewController, UITextViewDelegate, UINavigationControllerDelegate
在textField:
中键入时,此代码将使yourCustomTextField消失func textViewDidBeginEditing (_ textView: UITextView) {
if (textView.text == "Start typing...") {
textView.text = ""
textView.textColor = .black
}
textView.becomeFirstResponder()
}
func textViewDidEndEditing(_ textView: UITextView) {
if (textView.text == "") {
textView.text = "Start typing..."
textView.textColor = .lightGray
}
textView.resignFirstResponder()
}
答案 58 :(得分:0)
我刚刚发现,从iOS 10
开始,您现在可以将UITextView
实际转换为方法UITextField
,并在方法内设置占位符。刚刚尝试过它而无需继承UITextView
。
这是一个对我有用的例子:
-(void)customizeTextField:(UITextField *)textField placeholder:(NSString *)pText withColor:(UIColor *)pTextColor{
textField.attributedPlaceholder = [[NSAttributedString alloc]
initWithString:pText
attributes:@{NSForegroundColorAttributeName:pTextColor}];
}
要将它用于UITextView
,您只需使用类似的转换将其传递给方法:
[self customizeTextField:(UITextField*)_myTextView placeholder:@"Placeholder" withColor:[UIColor blackColor]];
N.B:经过测试后,我发现该解决方案在iOS9.x
上工作正常但导致iOS8.x
答案 59 :(得分:0)
通过查看(并尝试)大多数建议的解决方案,看看这个看似显而易见但缺失的UITextView功能,最好的&#39;我发现的最接近的是BobDickinson。但我不喜欢不得不求助于一个全新的子类[我更喜欢用于这种简单功能添加的插入类别],也没有截获UITextViewDelegate方法,这可能会破坏你现有的UITextView处理代码。所以,我采用了一个可以在任何现有UITextView实例上工作的插入类别...
#import <objc/runtime.h>
// Private subclass needed to override placeholderRectForBounds: to correctly position placeholder
@interface _TextField : UITextField
@property UIEdgeInsets insets;
@end
@implementation _TextField
- (CGRect)placeholderRectForBounds:(CGRect)bounds
{
CGRect rect = [super placeholderRectForBounds:bounds];
return UIEdgeInsetsInsetRect(rect, _insets);
}
@end
@implementation UITextView (Placeholder)
static const void *KEY;
- (void)setPlaceholder:(NSString *)placeholder
{
_TextField *textField = objc_getAssociatedObject(self, &KEY);
if (!textField) {
textField = [_TextField.alloc initWithFrame:self.bounds];
textField.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
textField.userInteractionEnabled = NO;
textField.font = self.font;
textField.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;
textField.insets = UIEdgeInsetsMake(self.textContainerInset.top,
self.textContainerInset.left + self.textContainer.lineFragmentPadding,
self.textContainerInset.bottom,
self.textContainerInset.right);
[self addSubview:textField];
[self sendSubviewToBack:textField];
objc_setAssociatedObject(self, &KEY, textField, OBJC_ASSOCIATION_RETAIN);
[NSNotificationCenter.defaultCenter addObserver:self selector:@selector(updatePlaceholder:) name:UITextViewTextDidChangeNotification object:nil];
}
textField.placeholder = placeholder;
}
- (NSString*)placeholder
{
UITextField *textField = objc_getAssociatedObject(self, &KEY);
return textField.placeholder;
}
- (void)updatePlaceholder:(NSNotification *)notification
{
UITextField *textField = objc_getAssociatedObject(self, &KEY);
textField.font = self.font;
[textField setAlpha:self.text.length? 0 : 1];
}
@end
它易于使用,只是显而易见的
UITextView *myTextView = UITextView.new;
...
myTextView.placeholder = @"enter text here";
它的工作原理是在正确的位置添加 UITextField - 在UITextView后面,并利用它的占位符代替(因此你不必担心获得正确的颜色等),然后在UITextView被更改为显示/隐藏此UITextField时监听通知(因此它不会干扰您现有的UITextViewDelegate调用)。并且没有涉及的神奇数字......: - )
objc_setAssociatedObject()/ objc_getAssociatedObject()是为了避免必须继承UITextView。 [不幸的是,为了正确定位UITextField,有必要引入一个私人&#39;子类,覆盖placeholderRectForBounds:]
改编自BobDickinson的Swift回答。
答案 60 :(得分:-1)
在UITextView PlaceholderTextView
中支持图标归属占位符的简单类@IBOutlet weak var tvMessage: PlaceholderTextView!
// TODO: - Create Icon Text Attachment
let icon: NSTextAttachment = NSTextAttachment()
icon.image = UIImage(named: "paper-plane")
let iconString = NSMutableAttributedString(attributedString: NSAttributedString(attachment: icon))
tvMessage.icon = icon
// TODO: - Attributes
let textColor = UIColor.gray
let lightFont = UIFont(name: "Helvetica-Light", size: tvMessage.font!.pointSize)
let italicFont = UIFont(name: "Helvetica-LightOblique", size: tvMessage.font!.pointSize)
// TODO: - Placeholder Attributed String
let message = NSAttributedString(string: " " + "Personal Message", attributes: [ NSFontAttributeName: lightFont!, NSForegroundColorAttributeName: textColor])
iconString.append(message)
// TODO: - Italic Placeholder Part
let option = NSAttributedString(string: " " + "Optional", attributes: [ NSFontAttributeName: italicFont!, NSForegroundColorAttributeName: textColor])
iconString.append(option)
tvMessage.attributedPlaceHolder = iconString
tvMessage.layoutSubviews()
答案 61 :(得分:-1)
修改占位符文本颜色的最简单方法是通过XCode故事板界面构建器。选择感兴趣的UITextField并打开右侧的身份检查器。单击“用户定义的运行时属性”中的加号,然后使用“键路径”添加一个新行作为_placeholderLabel.textColor,将“颜色和值”键入所需的颜色。
答案 62 :(得分:-1)
您只需在文本视图上设置标签即可。
<强> MyUITextView.h 强>
@interface MyUITextView : UITextView {
UILabel* _placeholderLabel;
}
@property(nonatomic, assign)NSString *placeholder;
<强> MyUITextView.m 强>
@implementation MyUITextView
- (id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
// Create placeholder
viewFrame = CGRectMake(0, 0, frame.size.width, 15);
_placeholderLabel = [[UILabel alloc] initWithFrame:viewFrame];
_placeholderLabel.textColor = [UIColor lightGrayColor];
[self addSubview:_placeholderLabel];
// Add text changed notification
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged:) name:UITextViewTextDidChangeNotification object:nil];
}
return self;
}
- (void)setPlaceholder:(NSString *)placeholder {
_placeholderLabel.text = placeholder;
}
- (NSString*)placeholder {
return _placeholderLabel.text;
}
#pragma mark UITextViewTextDidChangeNotification
- (void)textChanged:(NSNotification *)notification {
_placeholderLabel.hidden = ([self.text lenght] == 0);
}
@end
答案 63 :(得分:-4)
我能够在UITextView中添加一个“占位符”,代码少了很少。这就是我所做的:
UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(60, 800, 200, 60)];
textView.text = @"Write characters here...";
textView.textColor=[UIColor grayColor];
textView.font = [UIFont fontWithName:@"Hevlatica" size:15];
textView.delegate=self;
我想这不是一个真正的占位符,因为你必须在写之前删除文本,但如果你想要更简单的东西它可能会有所帮助。