#import "ViewController.h"
@interface ViewController ()<UITextViewDelegate>
@property (retain) UILabel* countLabel;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//创建多行文本输入框
UITextView* textview = [[UITextView alloc]initWithFrame:CGRectMake(0, 20, [UIScreen mainScreen].bounds.size.width, 60)];
//设置背景颜色
textview.backgroundColor = [UIColor grayColor];
//设置字体大小
textview.tag = 1;
textview.font = [UIFont systemFontOfSize:25];
//设置字体颜色
textview.textColor = [UIColor redColor];
//取消竖直的滑条
textview.showsVerticalScrollIndicator = NO;
[self.view addSubview:textview];
//设置代理
textview.delegate = self;
//创建手势
UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
//给self.view 加手势
[self.view addGestureRecognizer:tap];
_countLabel = [[UILabel alloc]initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width-50, 75, 50, 30)];
_countLabel.text = @"0/50";
[self.view addSubview:_countLabel];
}
-(void)tapAction:(UITapGestureRecognizer*)sender
{
UITextView* textView = (UITextView*)[self.view viewWithTag:1];
[textView resignFirstResponder];
}
#pragma mark- UITextViewDelegate
- (void)textViewDidBeginEditing:(UITextView *)textView
{
NSLog(@"开始编辑");
}
- (void)textViewDidEndEditing:(UITextView *)textView
{
NSLog(@"结束编辑");
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
NSLog(@"---text---:%@ %@",text,NSStringFromRange(range));
if (range.location > 49) {
return NO;
}
return YES;
}
- (void)textViewDidChangeSelection:(UITextView *)textView
{
NSLog(@"%lu",(unsigned long)textView.text.length);
NSString* str = [NSString stringWithFormat:@"%ld/%ld", textView.text.length,50-textView.text.length];
_countLabel.text = str;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
UITextView多行文本输入框
最新推荐文章于 2025-01-03 20:18:30 发布