自定义含Placeholder的UITextView

作者: 断剑 | 来源:发表于2016-07-14 21:14 被阅读239次

在我们的项目中经常会用到UITextView文本输入框,但是系统的textView没有想textFieldView一样有placeholder属性来方便我们的使用。今天把项目中自己写的一个自定义控件分享给大家

效果图
  • 先上代码
属性设计
//
//  ZZYPlaceholderTextView.m
//  VTEAM
//
//  Created by admin on 16/7/12.
//  Copyright © 2016年 断剑. All rights reserved.
//

#import "ZZYPlaceholderTextView.h"

@interface ZZYPlaceholderTextView()

@property (nonatomic, weak) UILabel * placeholderLabel;

@end

@implementation ZZYPlaceholderTextView

- (void)awakeFromNib
{
    [self setUp];
}

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame])
    {
        [self setUp];
    }
    return self;
    
}

- (void)setUp
{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textChange:) name:UITextViewTextDidChangeNotification object:self];
    CGFloat left = (self.leftMargin)?self.leftMargin:5;
    CGFloat top = (self.topMargin)?self.topMargin:5;
    CGFloat width = CGRectGetWidth(self.frame) - 2 * self.leftMargin;
    CGFloat height = (self.placeHeight)?self.placeHeight:21;
    UILabel * placeholderLabel = [[UILabel alloc]initWithFrame:CGRectMake(left, top, width,height)];
    placeholderLabel.textColor = (self.placeholderColor)?self.placeholderColor:[UIColor lightGrayColor];
    placeholderLabel.font = (self.placeholderFont)?self.placeholderFont:self.font;
    placeholderLabel.text = self.placeholder;
    [self addSubview:placeholderLabel];
    self.placeholderLabel = placeholderLabel;
}

- (void)textChange:(NSNotification *)nofi
{
    if (self.placeholder.length == 0 || [self.placeholder isEqualToString:@""]) {
        self.placeholderLabel.hidden = YES;
    }
    
    if (self.text.length > 0) {
        self.placeholderLabel.hidden = YES;
    }
    else
    {
        self.placeholderLabel.hidden = NO;
    }
    
}

- (void)setPlaceholder:(NSString *)placeholder
{
    _placeholder = placeholder;
    
    if (placeholder.length == 0 || [self.placeholder isEqualToString:@""]) {
        self.placeholderLabel.hidden = YES;
    }
    else
    {
        self.placeholderLabel.text = placeholder;
        self.placeholderLabel.hidden = NO;
    }
    
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}


@end
  • 思路分析

    • 在UITExtView内部创建一个label,在外部为label设置各种属性
  • 通过UITextView系统检测内部文字改变的通知,动态控制label的显示和隐藏状态

  • 使用方法

  • xib使用

    • 设置UITextView的类
    • 拖线设置属性
  • 代码用法

 ZZYPlaceholderTextView * placeView = [[ZZYPlaceholderTextView alloc]initWithFrame:CGRectMake(20, 350, self.view.frame.size.width - 40 , 100)];
   placeView.placeholder = @"请输入描述文字";
   [self.view addSubview:placeView];

相关文章

网友评论

本文标题:自定义含Placeholder的UITextView

本文链接:https://www.haomeiwen.com/subject/tftyjttx.html