UITextField是没有分行功能,如果先要输入多行文字,就需要用到UITextView,但是在使用UITextView的时候,我们也想给用户一个提示语,这个怎么实现呢??
说起UITextfield的placeholder,大家都不陌生,因为在UITextfield中有这个属性,之久给这个属性赋值,就可以实现提示的作用,但是在UITextView中你是否用过呢?, 在这里我告诉你UITextView是没有自带的placeholder这个属性的。如果想要实现这个功能就需要自己来实现。要如何实现呢?
下面是我实现的代码:
#import <UIKit/UIKit.h>
@interface MyTextViewPlaceholder : UITextView
@property (nonatomic, strong) NSString *placeholder;
@property (nonatomic, strong) UIColor *placeholderColor;
@end
============================================
#import "MyTextViewPlaceholder.h"
@implementation MyTextViewPlaceholder
/**
* 重写init方法 同时初始化一个通知,用来检测textView内容的改变
*/
- (instancetype)init
{
self = [super init];
if (self) {
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(setNeedsDisplay) name:UITextViewTextDidChangeNotification object:nil];
self.placeholder = @"";
self.placeholderColor = [UIColor redColor];
}
return self;
}
//绘制 placeholder的位置
-(void)drawRect:(CGRect)rect {
// if ([self.text isEqualToString:@""]) {
if (!self.hasText) {
CGRect placeholderRect;
//设置placeholder的位置
placeholderRect.origin.y = 8;
placeholderRect.size.height = CGRectGetHeight(self.frame) - 8;
placeholderRect.origin.x = 10;
placeholderRect.size.width = CGRectGetWidth(self.frame) - 10;
[self.placeholderColor set];
//绘制placeholder
[self.placeholder drawInRect:placeholderRect withAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14],NSForegroundColorAttributeName: _placeholderColor}];
}
}
//如果设置了为本内容 就重新绘制placeholder的内容
- (void)setText:(NSString *)text {
[super setText:text];
[self setNeedsDisplay];
}
@end
使用的时候直接初始化就可以了,然后直接设置placeholder的内容已经placeholder的颜色。 代码如下:
myPlaceholder = [MyTextViewPlaceholder new];
myPlaceholder.frame = CGRectMake(10, 100, self.view.frame.size.width - 40, 100);
//我在MyTextViewPlaceholder 中重写的时init方法,所以初始化的时候不能调用下面的方法
// MyTextViewPlaceholder * myPlaceholder =[[MyTextViewPlaceholder alloc]initWithFrame:CGRectMake(10, 100, self.view.frame.size.width - 40, 100)];
myPlaceholder.placeholder = @"12341234123412341234123412341234123412341234123412341234";
myPlaceholder.placeholderColor = [UIColor orangeColor];
myPlaceholder.delegate = self;
// myPlaceholder.text = @"改变后的";
[self.view addSubview:myPlaceholder];
到这里就完成了,这样就实现了UITextview 和UITextfield的placeholder一样的占位符功能