ios - 如何通过点击 UITextView ios 中的返回键来创建新行

标签 ios uitextview uitextviewdelegate

我刚接触 iPhone。我在我的应用程序中添加了一个使用 XIB 的 UITextView,现在在点击完成键后,它只是让键盘退出。但是,我想通过点击它来创建一个新行,这意味着它应该转到下一段。请帮助我实现我的输出。这是我的代码:

- (void)textViewDidEndEditing:(UITextView *)textView1
{
    if (![textView1 hasText]) {
        [textView1 addSubview:placeholderLabel];
    }
    else{
        NSLog(@"done button clicked!!");
    }

    CGRect rect;

    if(screenBounds.size.height == 568)//iPhone5
    {
        rect = CGRectMake(5, 76, 310, 491);
    }
    else{
        if(_kisiOS7){
            rect = CGRectMake(5, 76, 310, 404);
        }
        else{
            rect = CGRectMake(0, 44, 320, 436);
        }
    }

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3];

    txtView.frame = rect;

    [UIView commitAnimations];
}


- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if (range.length == 0) {
        if ([text isEqualToString:@"\n"]) {
            [textView resignFirstResponder];
            return NO;
        }
    }

    return YES;
}

提前致谢。

最佳答案

您应该使用返回值 NO 实现委托(delegate)方法(因此点击“返回”或“完成”不会关闭键盘)。

- (BOOL)textViewShouldEndEditing:(UITextView *)textView {
    return NO;
}

并删除或更改下一行代码的逻辑:

if (range.length == 0) {
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }
}

因此在 textViewShouldEndEditing 中,您可以确定/计算需要关闭键盘的情况(如果您要关闭 - 返回 YES,否则返回 - NO)

你也可以改变

的逻辑
  • (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {

if (range.length == 0) {
    if ([text isEqualToString:@"\n"]) {
        textView.text = [NSString stringWithFormat:@"%@\n\t",textView.text];
        return NO;
    }
}

在这种情况下,当用户点击键盘上的操作按钮(如“返回”)时。 Textview 将在文本中插入新行和附加制表符。

希望对您有所帮助。

关于ios - 如何通过点击 UITextView ios 中的返回键来创建新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29587912/

相关文章:

iphone - iOS 开发 : What's a simple way to calculate the number of seconds that have passed between two events?

objective-c - iOS 应用程序 NSInvalidArgumentException

iphone - 未调用 UITextViewDelegate 方法(UITableViewCell 中的 UITextView)

ios - 如何设置 "if there is text in text view"

ios - UITableView 滚动前单元格大小错误?

objective-c - iOS:简单的 NSMutableArray 调用

ios - 在不删除粗体/下划线/斜体格式的情况下更改 UITextView 字体

ios - 更改整个应用程序的键盘外观

ios - 替换 UITextView 的部分属性文本

ios - 如何在 swift 中从 uitableview 转至 uitextview 并使用 nsattributedtext 属性