UITextView

最后更新于:2022-04-01 06:59:26

~~~ 1.创建并初始化 @property (nonatomic, strong) UITextView *textView; // 创建 self.textView = [[UITextView alloc] initWithFrame:self.view.frame]; // 设置textview里面的字体颜色 self.textView.textColor = [UIColor blackColor]; // 设置字体名字和字体大小 self.textView.font = [UIFont fontWithName:@"Arial" size:18.0]; // 设置代理 self.textView.delegate = self; // 设置它的背景颜色 self.textView.backgroundColor = [UIColor whiteColor]; self.textView.text = @“hehe”; // 返回键的类型 self.textView.returnKeyType = UIReturnKeyDefault; // 键盘类型 self.textView.keyboardType = UIKeyboardTypeDefault; // 是否可以拖动 self.textView.scrollEnabled = YES; 2. UITextView退出键盘的几种方式 (1)如果你程序是有导航条的,可以在导航条上面加多一个Done的按钮,用来退出键盘,当然要先实现UITextViewDelegate。 - (void)textViewDidBeginEditing:(UITextView *)textView { self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(getOverEditing)]; } - (void)textViewDidEndEditing:(UITextView *)textView { self.navigationItem.rightBarButtonItem = nil; } - (void)getOverEditing{ [self.textView resignFirstResponder]; } (2)如果你的textview里不用回车键,可以把回车键当做退出键盘的响应键。 #pragma mark - UITextView Delegate Methods -(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text { if ([text isEqualToString:@"\n"]) { [textView resignFirstResponder]; return NO; } return YES; } (3)还有你也可以自定义其他视图控件加载到键盘上用来退出,比如在弹出的键盘上面加一个view来放置退出键盘的Done按钮。 UIToolbar * topView = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 30)]; UIBarButtonItem * cancelButton= [[UIBarButtonItem alloc]initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(dismissKeyBoard)]; NSArray * buttonsArray = @[cancelButton]; [topView setItems:buttonsArray]; [self.textView setInputAccessoryView:topView]; -(void)dismissKeyBoard { [tvTextView resignFirstResponder]; } 3.UITextView自定选择文字后的菜单 在ViewDidLoad中加入: - (void)viewDidLoad { [super viewDidLoad]; self._textView = [[UITextView alloc] initWithFrame:CGRectMake(10, 100, 300, 200)]; [self.view addSubview:_textView]; UIMenuItem *menuItem = [[UIMenuItem alloc]initWithTitle:@“我是自定义的菜单" action:@selector(didClickCustomMenuAction)]; UIMenuController *menu = [UIMenuController sharedMenuController]; [menu setMenuItems:[NSArray arrayWithObject:menuItem]]; [menuItem release]; } 当然上面那个@selector里面的changeColor方法还是自己写吧,也就是说点击了我们自定义的菜单项后会触发的方法。 然后还得在代码里加上一个方法: -(BOOL)canPerformAction:(SEL)action withSender:(id)sender { if(action ==@selector(changeColor) || action == @selector(copy:)) { if(_textView.selectedRange.length>0) return YES; } return NO; } -(void)didClickCustomMenuAction { NSLog(@"%@“,__function__); } ~~~
';