作者:jia19891213 | 来源:互联网 | 2023-06-11 17:26
AJ分享,必须精品一:效果二:代码:由于系统自带的UITextField:和UITextView:不能满足我们的需求,所以我们需要自己设计一个。UITextField:1.文字永远是一行,不能显示
AJ分享,必须精品
一:效果
二:代码:
由于系统自带的UITextField:和UITextView:不能满足我们的需求,所以我们需要自己设计一个。
UITextField:
1.文字永远是一行,不能显示多行文字
2.有placehoder属性设置占位文字
3.继承自UIControl
4.监听行为
1> 设置代理
2> addTarget:action:forControlEvents:
3> 通知:UITextFieldTextDidChangeNotification
UITextView:
1.能显示任意行文字
2.不能设置占位文字
3.继承自UIScollView
4.监听行为
1> 设置代理
2> 通知:UITextViewTextDidChangeNotification
NYTextView.h
#import
@interface NYTextView : UITextView
/** 占位文字 */
@property (nonatomic, copy) NSString *placeholder;
/** 占位文字的颜色 */
@property (nonatomic, strong) UIColor *placeholderColor;
@end
NYTextView.m
#import "NYTextView.h"
@implementation NYTextView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[NYNotificationCenter addObserver:self selector:@selector(textDidChange) name:UITextViewTextDidChangeNotification object:self];
}
return self;
}
- (void)dealloc
{
[NYNotificationCenter removeObserver:self];
}
- (void)textDidChange
{
[self setNeedsDisplay];
}
- (void)setPlaceholder:(NSString *)placeholder
{
_placeholder = [placeholder copy];
[self setNeedsDisplay];
}
- (void)setPlaceholderColor:(UIColor *)placeholderColor
{
_placeholderColor = placeholderColor;
[self setNeedsDisplay];
}
- (void)setText:(NSString *)text
{
[super setText:text];
[self setNeedsDisplay];
}
- (void)setFont:(UIFont *)font
{
[super setFont:font];
[self setNeedsDisplay];
}
- (void)drawRect:(CGRect)rect
{
if (self.hasText) return;
NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
attrs[NSFontAttributeName] = self.font;
attrs[NSForegroundColorAttributeName] = self.placeholderColor?self.placeholderColor:[UIColor grayColor];
CGFloat x = 5;
CGFloat w = rect.size.width - 2 * x;
CGFloat y = 8;
CGFloat h = rect.size.height - 2 * y;
CGRect placeholderRect = CGRectMake(x, y, w, h);
[self.placeholder drawInRect:placeholderRect withAttributes:attrs];
}
@end