UITextView多行文本輸入框

這裏寫圖片描述

#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
發佈了48 篇原創文章 · 獲贊 1 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章