天天看点

UITextView自定义封装(带placeHolder)

  • 根据我们的开发需求, 有时候UITextField不足以满足我们, 比如多行输入时, 不得不使用新的控件.
  • 本篇文章对UITextView进行了重写和封装, 希望可以帮助大家.

重新定义封装UITextView

使用方法

常见问题

注意: PlaceHolderTextView为作者所起的名字, 可以随便叫什么

UITextView重写封装

/* .h文件  */
#import <UIKit/UIKit.h>

@interface PlaceHolderTextView : UITextView

@property (nonatomic, strong) NSString *placeholder;  /* 灰色提示文字, 用于外部调用时添加的占位字符 */

@end
           
/* .m文件 */
#import "PlaceHolderTextView.h"

@implementation PlaceHolderTextView

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

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

#pragma mark 注册通知
- (void)addObserver {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidBeginEditing:) name:UITextViewTextDidBeginEditingNotification object:self];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidEndEditing:) name:UITextViewTextDidEndEditingNotification object:self];
}

#pragma mark 移除通知
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark 开始编辑
- (void)textDidBeginEditing:(NSNotification *)notification {
    if ([super.text isEqualToString:_placeholder]) {
        super.text = @"";
        [super setTextColor:[UIColor blackColor]];
    }
}

#pragma mark 结束编辑
- (void)textDidEndEditing:(NSNotification *)notification {
    if (super.text.length == ) {
        super.text = _placeholder;
        /* 如果文本框内是原本的提示文字,则显示灰色字体 */
        [super setTextColor:[UIColor lightGrayColor]];
    }
}

#pragma mark 重写setPlaceholder方法
- (void)setPlaceholder:(NSString *)aPlaceholder {
    _placeholder = aPlaceholder;
    [self textDidEndEditing:nil];
}

#pragma mark 重写getText方法
- (NSString *)text {
    NSString *text = [super text];
    if ([text isEqualToString:_placeholder]) {
        return @"";
    }
    return text;
}

@end
           

使用

self.feedBackTextView = [[PlaceHolderTextView alloc] initWithFrame:CGRectMake(, , , )]; /* 给出尺寸 */
    [self.view addSubview:self.feedBackTextView];
    [self.feedBackTextView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.view.mas_top).with.offset();
        make.width.equalTo(@355);
        make.height.equalTo(@150);
    }];/* 添加约束 */
    self.feedBackTextView.placeholder = @"亲, 您遇到什么系统问题啦, 或者有什么功能建议吗? 欢迎提给我们, 谢谢!"; /* 添加占位字符和TextField的placeholder 一样的使用方式 */
           
/* 如果需要圆角和边框这里设置 */
    self.feedBackTextView.layer.borderWidth = ;
    self.feedBackTextView.layer.borderColor = [UIColor grayColor].CGColor;
    /* 设置圆角 */
    self.feedBackTextView.layer.cornerRadius = ;
    self.feedBackTextView.font = [UIFont systemFontOfSize:];
           

常见问题

比较常见的就是使用时 输入的文字居中显示 不像别人APP 中的靠上显示。
/* 关闭视图的自适应就可以了 */
 self.automaticallyAdjustsScrollViewInsets = NO;