oc -- 自定义textview

前言:系统自带的textview是没有添加占位文字的功能的,我们可以通过自定义即可实现此功能

  • 自定义textview
#import 

@interface TextView : UITextView
/** 占位文字 */
@property(nonatomic, copy) NSString *placeholder;
/** 占位文字颜色 */
@property(nonatomic, strong) UIColor *placeholderColor;
@end
#import "TextView.h"

@implementation TextView

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        // 设置默认字体
        self.font = [UIFont systemFontOfSize:17];
        // 设置默认颜色
        self.placeholderColor = [UIColor grayColor];
        // 使用通知监听文字改变
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange:) name:UITextViewTextDidChangeNotification object:self];
    }
    return self;
}
- (void)textDidChange:(NSNotification *)note
{
    // 会重新调用drawRect:方法
    [self setNeedsDisplay];
}
- (void)dealloc
{
    //移除通知
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
// 每次调用drawRect:方法,都会将以前画的东西清除掉
- (void)drawRect:(CGRect)rect
{
    // 如果有文字,就直接返回,不需要画占位文字
    if (self.hasText) return;
    // 属性
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSFontAttributeName] = self.font;
    attrs[NSForegroundColorAttributeName] = self.placeholderColor;
    // 画文字 光标与文字不一致,设置尺寸
    rect.origin.x = 5;
    rect.origin.y = 8;
    rect.size.width -= 2 * rect.origin.x;
    [self.placeholder drawInRect:rect withAttributes:attrs];
}
- (void)layoutSubviews
{
    [super layoutSubviews];
    
    [self setNeedsDisplay];
}
#pragma mark - setter
//重写setter方法调用setNeedsDisplay方法刷新
- (void)setPlaceholder:(NSString *)placeholder
{
    _placeholder = [placeholder copy];
    
    [self setNeedsDisplay];
}
- (void)setPlaceholderColor:(UIColor *)placeholderColor
{
    _placeholderColor = placeholderColor;
    
    [self setNeedsDisplay];
}
- (void)setFont:(UIFont *)font
{
    [super setFont:font];
    
    [self setNeedsDisplay];
}
- (void)setText:(NSString *)text
{
    [super setText:text];
    
    [self setNeedsDisplay];
}
- (void)setAttributedText:(NSAttributedString *)attributedText
{
    [super setAttributedText:attributedText];
    
    [self setNeedsDisplay];
}


@end

  • 在外部调用
#import "ViewController.h"
#import "TextView.h"
@interface ViewController ()
@property(nonatomic, strong) TextView *textView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    TextView *textView = [[TextView alloc] init];
    textView.frame = self.view.bounds;
    //设置可以上下拖动
    textView.alwaysBounceVertical = YES;
    textView.delegate = self;
    textView.placeholder = @"我是占位文字....我是占位文字....我是占位文字....我是占位文字....我是占位文字....我是占位文字....哈哈哈";
    [self.view addSubview:textView];
    self.textView = textView;
    
  
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end

有没有帮到你呢?
(欢迎大家对不合适的地方进行指正,看完觉得有帮到你给点个赞吧)

你可能感兴趣的:(oc -- 自定义textview)