iOS UI-文本视图(UITextView)

本文介绍如何在 iOS 应用中使用 UITextView 控件实现文本输入功能,并通过手势识别关闭键盘,调整键盘类型及文本视图的高度。
 1 #import "ViewController.h"
 2 
 3 @interface ViewController ()<UITextViewDelegate>
 4 
 5 @property (strong, nonatomic) UITextView *textView;
 6 
 7 @end
 8 
 9 @implementation ViewController
10 
11 @synthesize textView;
12 
13 - (void)viewDidLoad {
14     [super viewDidLoad];
15     //创建视图
16     UIView *bgView = [[UIView alloc] initWithFrame:self.view.frame];
17     bgView.backgroundColor = [UIColor lightGrayColor];
18     [self.view addSubview:bgView];
19     //创建点击手势
20     UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeKeyBoard)];
21     [bgView addGestureRecognizer:tap];
22     
23     //初始化大小
24     self.textView = [[UITextView alloc] initWithFrame:CGRectMake(50, 150, self.view.frame.size.width-100, 300)];
25     //字体颜色
26     self.textView.textColor = [UIColor blackColor];
27     //字体名称和大小
28     self.textView.font = [UIFont fontWithName:@"Arial" size:18.0];
29     //设置委托方法
30     self.textView.delegate = self;
31     //背景颜色
32     self.textView.backgroundColor = [UIColor whiteColor];
33     //内容
34     //self.textView.text = @"qwertyuyiopasdfghjklzxcvbnm";
35     //返回键类型
36     self.textView.returnKeyType = UIReturnKeyDefault;
37     //键盘类型
38     self.textView.keyboardType = UIKeyboardTypeNamePhonePad;
39     //是否可以拖动
40     self.textView.scrollEnabled = YES;
41     //禁止编辑
42     self.textView.editable = YES;
43     //自适应高度
44     self.textView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
45     //加到整个页面中
46     [self.view addSubview:self.textView];
47 }
48 
49 - (void)closeKeyBoard
50 {
51     [self.textView resignFirstResponder];
52 }
53 - (void)textViewDidBeginEditing:(UITextView *)textView
54 {
55     [UIView beginAnimations:@"test" context:nil];
56     [UIView setAnimationDuration:0.3];
57     
58     CGRect rect = self.textView.frame;
59     rect.origin.y = rect.origin.y - 80;
60     self.textView.frame = rect;
61     [UIView commitAnimations];
62 }
63 
64 - (void)textViewDidEndEditing:(UITextView *)textView
65 {
66     [UIView beginAnimations:@"test" context:nil];
67     [UIView setAnimationDuration:0.3];
68     
69     CGRect rect = self.textView.frame;
70     rect.origin.y = rect.origin.y + 80;
71     self.textView.frame = rect;
72     [UIView commitAnimations];
73 }
74 
75 - (void)didReceiveMemoryWarning {
76     [super didReceiveMemoryWarning];
77     // Dispose of any resources that can be recreated.
78 }
79 
80 @end

 

转载于:https://www.cnblogs.com/oc-bowen/p/5091959.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值