UITextView多行文本输入框

本文主要介绍了在iOS应用开发中如何利用UITextView组件创建一个多行文本输入框,包括设置最大行数、文字编辑样式以及交互功能的实现,帮助开发者提升用户体验。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这里写图片描述

#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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值