iOS控件之UITextView字数控制以及占位符的实现

下面介绍 UITextView 的字数控制,占位符,以及键盘回退方法.

1.字数控制实现

#import "ViewController.h"

#define kScreenWidth [UIScreen mainScreen].bounds.size.width

@interface ViewController ()<UITextViewDelegate>

/** textView */
@property (nonatomic, weak) UITextView *textView;

/** placeHoldLabel */
@property (nonatomic, weak) UILabel *placeHoldLabel;

/** noticeLabel */
@property (nonatomic, weak) UILabel *noticeLabel;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(0, 64, kScreenWidth, 200)]; //初始化大小并自动释放

    _textView = textView;

    textView.textColor = [UIColor blackColor];//设置字体颜色

    textView.font = [UIFont fontWithName:@"Arial" size:18.0];//设置 字体 和 大小

    textView.delegate = self;// 设置控制器为 textView 的代理方法

    textView.backgroundColor = [UIColor lightGrayColor];//设置它的背景颜色

    textView.returnKeyType = UIReturnKeyDefault;//返回键的类型

    textView.keyboardType = UIKeyboardTypeDefault;//键盘类型

    textView.scrollEnabled = YES;//是否可以拖动

    [self.view addSubview:textView];


    UILabel *placeHoldLabel = [[UILabel alloc]initWithFrame:CGRectMake(5, 5, kScreenWidth, 25)];

    self.placeHoldLabel = placeHoldLabel;

    placeHoldLabel.font = [UIFont systemFontOfSize:18];

    placeHoldLabel.enabled = NO;

    placeHoldLabel.text = @"请输入您的内容...";

    placeHoldLabel.numberOfLines=0;

    placeHoldLabel.font =  [UIFont systemFontOfSize:12];

    [self.textView addSubview:placeHoldLabel];


    UILabel *noticeLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 280, kScreenWidth * 0.95, 20)];

    self.noticeLabel = noticeLabel;

    noticeLabel.textAlignment = NSTextAlignmentRight;

    noticeLabel.text = @"您还可以输入200字!";

    [self.view addSubview:noticeLabel];
}

#pragma mark - 2.textView delegate
-(void)textViewDidChange:(UITextView *)textView
{
    if ([self.textView.text length] == 0) {
        [self.placeHoldLabel setHidden:NO];
    }else{
        [self.placeHoldLabel setHidden:YES];
    }
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{

    if([text isEqualToString:@"\n"]){

        [textView resignFirstResponder];

        return NO;
    }

    if (range.location>=200){

        self.noticeLabel.text=@"还能输入0字";
        return  NO;
    } else {

        self.noticeLabel.text=[NSString stringWithFormat:@"还能输入%lu字",200-range.location];
        return YES;
    }
}
@end
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值