## 一:效果

## 二:代碼:
由于系統自帶的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
~~~
- 前言
- (1)微博主框架-子控制器的添加
- (2)微博主框架-自定義導航控制器NavigationController
- (3)微博主框架-UIImage防止iOS7之后自動渲染_定義分類
- (4)微博自定義tabBar中間的添加按鈕
- (5)微博自定義搜索框searchBar
- (6)導航控制器NavigationController 的滑動回退功能實現
- (7)程序啟動新特性用UICollectionViewController實現
- (8)用AFNetworking和SDWebImage簡單加載微博數據
- (9)微博模型之時間相關重要操作,判斷剛剛,昨天,今年等等
- (10)微博cell中圖片的顯示以及各種填充模式簡介
- (11)發送微博自定義TextView實現帶占位文字
- (12)發送微博自定義工具條代理實現點擊事件
- (13)發送微博調用相機里面的圖片以及調用相機