iOS实现UITextView的placeholder和输入字数限制的实现

相当于常见的反馈意见功能,要求有如下4点:

1.输入文字的时候提示文字消失,TextView没有文字的时候提示文字显示;
2.右下角实时显示字数;
3.字数到达指定限制后,TextView不能输入更多,可以删除;
4.提交按钮在TextView不为空的时候按钮为绿色且可点击;TextView为空时,为灰色状态且不可点击。

效果:


textViewSetting

代码实现:

//  ViewController.m
//  DHTextViewSetting
//
//  Created by 邓昊 on 2017/12/7.
//  Copyright © 2017年 邓昊. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()<UITextViewDelegate>
@property (weak, nonatomic) IBOutlet UILabel *placeHolder;
@property (weak, nonatomic) IBOutlet UIButton *commitButton;
@property (weak, nonatomic) IBOutlet UITextView *feedBackTextView;
@property (weak, nonatomic) IBOutlet UILabel *stirngLenghLabel;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.feedBackTextView.delegate = self;
    self.placeHolder.userInteractionEnabled = NO;
    self.commitButton.userInteractionEnabled = NO;
    self.placeHolder.text = @"请输入您的意见...";
    
    self.feedBackTextView.layer.borderWidth = 0.5;
    self.feedBackTextView.layer.borderColor = [UIColor lightGrayColor].CGColor;
}

#pragma mark - UITextViewDelegate
//正在改变
- (void)textViewDidChange:(UITextView *)textView {
    NSLog(@"%@", textView.text);
    self.placeHolder.hidden = YES;
    //允许提交按钮点击操作
    self.commitButton.backgroundColor = [UIColor blueColor];
    self.commitButton.userInteractionEnabled = YES;
    //实时显示字数
    self.stirngLenghLabel.text = [NSString stringWithFormat:@"%lu/20", (unsigned long)textView.text.length];
    //字数限制操作
    if (textView.text.length >= 20) {
        textView.text = [textView.text substringToIndex:20];
        self.stirngLenghLabel.text = @"20/20";
    }
    //取消按钮点击权限,并显示提示文字
    if (textView.text.length == 0) {
        self.placeHolder.hidden = NO;
        self.commitButton.userInteractionEnabled = NO;
        self.commitButton.backgroundColor = [UIColor lightGrayColor];
    }
}

@end
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,803评论 25 709
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,262评论 4 61
  • 果然,吃多了零食体重就会暴涨。今天早上望着体重称上的数字,默默地把这份错给认了,也很愉快的接受这种惩罚。 对的,凡...
    云小事阅读 205评论 0 0
  • 最近心情稍有灰暗,今天来图书室看了《哈佛情商课》一书,找到了些认同感。生活很美好,对于情绪应灵活调节,张弛有度。
    我有嘉宾阅读 338评论 0 0
  • 想想这几年已经走过了很多路,到了很多地方,见到了许多的人。见过喜爱的,有意义的,最终有的颓败,有的消散。我...
    Nicole慕达阅读 320评论 0 0