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一樣的佔位符功能