1、自定义UITextView(将UITextView和UILabel想结合使用)
使用UITextView的时候需要在text显示一段提示文字,但是UITextView没有像UITextField一样的 placehoder属性对其进行设置,因此需要将将UITextView和UILabel相结合使用,自定义一个UITextView。
1、创建textView类继承于UITextView
2、在initWithFrame:(CGRect)frame中添加UILabel
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.backgroundColor = [UIColor clearColor];
// Initialization code
UILabel *placehoderLabel = [[UILabel alloc]init];
[self addSubview:placehoderLabel];
self.placehoderLabel = placehoderLabel;
//设置textView(self)的背景色为clearColor
self.backgroundColor = [UIColor clearColor];
//设置label的背景色为clearColor
placehoderLabel.backgroundColor = [UIColor clearColor];
placehoderLabel.numberOfLines = 0;
}
return self;
}
3、设置label的frame
- (void)layoutSubviews
{
[super layoutSubviews];
self.placehoderLabel.x = 5;
self.placehoderLabel.y = 7;
self.placehoderLabel.width = self.width - self.placehoderLabel.x;
CGSize maxSize = CGSizeMake(self.placehoderLabel.width, MAXFLOAT);
CGSize placehoderSize = [self.placehoder sizeWithFont:self.placehoderLabel.font constrainedToSize:maxSize];
self.placehoderLabel.height = placehoderSize.height;
}
4、定义外部属性,其他人可以对textView的placehoder和placehoderColor进行修改
@property (nonatomic,copy)NSString *placehoder;
@property (nonatomic,strong)UIColor *placehoderColor;
5、重写两个属性的set方法提供给外部的方法可以对这些属性对其进行设置
-(void)setPlacehoderColor:(UIColor *)placehoderColor
{
_placehoderColor = placehoderColor;
self.placehoderLabel.textColor = _placehoderColor;
}
- (void)setPlacehoder:(NSString *)placehoder
{
#warning 如果是copy set最好这样写
_placehoder = [placehoder copy];
self.placehoderLabel.text = placehoder;
//重新刷新frame (当在中途换了文字需要重新计算frame)
[self setNeedsLayout];
}
6、设置监听,监听textView的文本信息改变的监听
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
//当self的文字发生改变 self就会自动发出一个UITextViewTextDidChangeNotification通知
[center addObserver:self selector:@selector(textDidChange) name:UITextViewTextDidChangeNotification object:self];
7、设置label的显示与隐藏
当有文本信息输入的时候,将label隐藏
- (void)textDidChange
{
self.placehoderLabel.hidden = (self.text.length != 0);
}
8、重写setFont方法防止其他人在使用的时候 修改字体大小
- (void)setFont:(UIFont *)font
{
[super setFont:font];
self.placehoderLabel.font = font;
//重新刷新frame (当在中途换了文字需要重新计算frame)
[self setNeedsLayout];
}