AJ学IOS 之微博项目实战(11)发送微博自定义TextView实现带占位文字

时间:2022-08-23 20:11:05

AJ分享,必须精品

一:效果

AJ学IOS 之微博项目实战(11)发送微博自定义TextView实现带占位文字

二:代码:

由于系统自带的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

//
// Created by apple on 14-10-20.
// Copyright (c) 2014年 heima. All rights reserved.
// 增强:带有占位文字 #import <UIKit/UIKit.h> @interface NYTextView : UITextView
/** 占位文字 */
@property (nonatomic, copy) NSString *placeholder;
/** 占位文字的颜色 */
@property (nonatomic, strong) UIColor *placeholderColor;
@end

NYTextView.m


// Created by apple on 14-10-20.
// Copyright (c) 2014年 heima. All rights reserved.
// #import "NYTextView.h" @implementation NYTextView - (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// 不要设置自己的delegate为自己
// self.delegate = self; // 通知
// 当UITextView的文字发生改变时,UITextView自己会发出一个UITextViewTextDidChangeNotification通知
[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]; // setNeedsDisplay会在下一个消息循环时刻,调用drawRect:
[self setNeedsDisplay];
} - (void)setFont:(UIFont *)font
{
[super setFont:font]; [self setNeedsDisplay];
} - (void)drawRect:(CGRect)rect
{
// [NYRandomColor set];
// UIRectFill(CGRectMake(20, 20, 30, 30));
// 如果有输入文字,就直接返回,不画占位文字
if (self.hasText) return; // 文字属性
NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
attrs[NSFontAttributeName] = self.font;
attrs[NSForegroundColorAttributeName] = self.placeholderColor?self.placeholderColor:[UIColor grayColor];
// 画文字
// [self.placeholder drawAtPoint:CGPointMake(5, 8) withAttributes:attrs];
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