效果图:
h文件
@interface YLTextView : UITextView
@property (copy ,nonatomic)NSString *placeHoder;
@property (assign,nonatomic)BOOL hidePlaceHoder; //是否对placeHoder进行隐藏
@end
m 文件
//
// YLTextView.m
// YangLand
//
// Created by 赵大财 on 16/3/13.
// Copyright © 2016年 tshiny. All rights reserved.
//
#import "YLTextView.h"
@interface YLTextView ()
@property (weak ,nonatomic)UILabel *placeHoderLabel;
@end
@implementation YLTextView
- (instancetype)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
self.font = [UIFont systemFontOfSize:13];
}
return self;
}
-(void)setFont:(UIFont *)font {
[super setFont:font];
self.placeHoderLabel.font = font;
[self.placeHoderLabel sizeToFit]; //文字的大小 就是label的尺寸
}
-(void)setPlaceHoder:(NSString *)placeHoder {
_placeHoder = placeHoder;
self.placeHoderLabel.text = placeHoder;
[self.placeHoderLabel sizeToFit];
}
- (void)setHidePlaceHoder:(BOOL)hidePlaceHoder {
_hidePlaceHoder = hidePlaceHoder;
self.placeHoderLabel.hidden = hidePlaceHoder;
}
- (UILabel *)placeHoderLabel {
if (!_placeHoderLabel) {
UILabel *placeHoderLabel = [[UILabel alloc]init];
[self addSubview:placeHoderLabel];
_placeHoderLabel = placeHoderLabel;
}
return _placeHoderLabel;
}
- (void)layoutSubviews {
[super layoutSubviews];
self.placeHoderLabel.x = 10;
self.placeHoderLabel.y = 10;
}
@end
控制器的使用
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChange) name:UITextViewTextDidChangeNotification object:nil]; //监听文字改变
//文字改变方法
- (void)textChange {
if (self.textView.text.length) {
_textView.hidePlaceHoder = YES;
}else {
_textView.hidePlaceHoder = NO;
}
}
- (YLTextView *)textView {
if (!_textView) {
_textView = [[YLTextView alloc]initWithFrame:self.view.bounds];
_textView.delegate = self;
_textView.alwaysBounceVertical = YES; //这是让textView可上下滑动
_textView.placeHoder = @"请发表今天的心情...";
_textView.font = [UIFont systemFontOfSize:20];
}
return _textView;
}