如何在聊天中创建成长和缩小UITextView?

时间:2015-12-03 15:37:39

标签: ios objective-c uitableview uitextview

我试图创建一个不断增长和缩小的UITextView,我尝试了一些示例代码,我可以看到它的增长,但它没有缩小。

当我输入文本时它会增长,但是当我从UITextView中删除相同的文本时,它不会缩小回相同的旧尺寸。 这是用于增长UITextView

的工作代码
int returnPressed = 0;
int newLine;

@interface dynamicViewController () <UITextViewDelegate>
{

    IBOutlet UIView *dock;
    IBOutlet UITextView *textView1;
    CGRect previousRect;

}






- (UITableViewCell *)tableView:(UITableView *)tableView1 cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *MyIdentifier;
   // NSLog(@"%@",selectedTabFields);
    if([[[selectedTabFields valueForKey:@"type"] objectAtIndex:indexPath.row] isEqualToString:@"VARCHAR"]){
        MyIdentifier = @"CharCell";

    }
    cell= [tableView1 dequeueReusableCellWithIdentifier:MyIdentifier];

    if (cell == nil)
    {
        cell = [[dynamicCell alloc] initWithStyle:UITableViewCellStyleDefault
                               reuseIdentifier:MyIdentifier];
           cell.selectionStyle=UITableViewCellSelectionStyleNone;


            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.accessoryType = UITableViewCellAccessoryNone;

                [cell.contentView addSubview:[self getLabel:indexPath.row]];

            if([[[selectedTabFields valueForKey:@"type"] objectAtIndex:indexPath.row] isEqualToString:@"VARCHAR"]){

                [cell.contentView addSubview:[self getVarcharTextView:indexPath.row]];
            }

    }


    return cell;

}


//Varchar UITextView
-(UITextView *)getVarcharTextView:(NSUInteger)index{
    UITextField *textField;
    if(IS_IPHONE_5){
        textView1= [[UITextView alloc] initWithFrame:CGRectMake(15,40,cell.frame.size.width-30,cell.frame.size.height)];
    }else if(IS_IPHONE_6){
        textView1= [[UITextView alloc] initWithFrame:CGRectMake(15,40,340,cell.frame.size.height)];

    }
    previousRect = CGRectZero;

    textView1.delegate = self;

    textView1.layer.borderWidth = 0.0f;
    textView1.layer.borderColor = [[UIColor clearColor] CGColor];
    textView1.layer.cornerRadius = 4;
    textView1.backgroundColor=[UIColor colorWithRed:249.0/255.0 green:249.0/255.0 blue:249.0/255.0 alpha:1];
    textView1.textColor = [UIColor lightGrayColor];
    textView1.text = @"Place Holder";
    return textView1;

}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    if ([text isEqualToString:@"\n"]) {

        returnPressed +=1;

        if(returnPressed < 17){

            textView1.frame = CGRectMake(8, 8, textView1.frame.size.width, textView1.frame.size.height + 17);

            newLine = 17*returnPressed;

            [UIView animateWithDuration:0.1 animations:^
             {
                 dock.transform = CGAffineTransformMakeTranslation(0, -250 - newLine);
             }
             ];

        }
    }

    return YES;
}


- (void)textViewDidChange:(UITextView *)textView{

    UITextPosition* pos = textView1.endOfDocument;

    CGRect currentRect = [textView1 caretRectForPosition:pos];

    if (currentRect.origin.y > previousRect.origin.y || [textView1.text isEqualToString:@"\n"]){

        returnPressed +=1;

        if(returnPressed < 17 && returnPressed > 1){

            textView1.frame = CGRectMake(8, 8, textView1.frame.size.width, textView1.frame.size.height + 17);

            newLine = 17*returnPressed;

            [UIView animateWithDuration:0.1 animations:^
             {
                 dock.transform = CGAffineTransformMakeTranslation(0, -250 - newLine);
             }
             ];

        }
    }
    previousRect = currentRect;


}



- (BOOL)textViewShouldBeginEditing:(UITextView *)textField {


    if([textView1.text isEqualToString:@""] || [textView1.text isEqualToString:@"Place Holder"]){
        textView1.text = @"";
    }

    textView1.textColor = [UIColor blackColor];

    [UIView animateWithDuration:0.209 animations:^
     {
         dock.transform = CGAffineTransformMakeTranslation(0, -200 - newLine);
     }
                     completion:^(BOOL finished){}];

    return YES;
}

请帮助完善它。

1 个答案:

答案 0 :(得分:0)

我现在正在一个聊天应用上工作,这就是我正在做的事情。

下载此库HPGrowingTextView

将所需文件拖放到项目中。

使用cocoapods下载IQKeyboardManager

现在拖放一个UIView而不是UITextView,并在界面构建器中将UIView的自定义类设置为“ HPGrowingTextView

现在第一个库是针对ios 7及以下的,所以他编写了很多代码。我所做的是,删除了一些代码。检查下面的代码。

@interface ChatMessagesViewController ()<HPGrowingTextViewDelegate,UITableViewDelegate,UITableViewDataSource>
{
    IBOutlet UIView *containerView;
    IBOutlet HPGrowingTextView *msgTextView;
}

containerView 是一个UIView,由发送/完成按钮和msgTextView组成。

-(void)viewDidLoad 
{
         [super viewDidLoad];
         msgTextView.isScrollable = NO;
         msgTextView.contentInset = UIEdgeInsetsMake(0, 5, 0, 5);
         msgTextView.layer.cornerRadius = 5.0;
         msgTextView.layer.masksToBounds = YES;
         msgTextView.minNumberOfLines = 1;
         msgTextView.maxNumberOfLines = 5;
         // you can also set the maximum height in points with maxHeight
         // msgTextView.maxHeight = 200.0f;
         msgTextView.returnKeyType = UIReturnKeyGo; //just as an example
         msgTextView.font = [UIFont systemFontOfSize:15.0f];
         msgTextView.delegate = self;
         msgTextView.internalTextView.scrollIndicatorInsets = UIEdgeInsetsMake(5, 0, 5, 0);
         //    msgTextView.backgroundColor = [UIColor whiteColor];
         msgTextView.placeholder = @"Enter Message";
}
-(void)growingTextView:(HPGrowingTextView *)growingTextView willChangeHeight:(float)height
{
    float diff = (growingTextView.frame.size.height - height);

    CGRect r = containerView.frame;
    r.size.height -= diff;
    containerVwHeightConstraint.constant -= diff;
    r.origin.y += diff;
    containerView.frame = r;
}

将此代码放在AppDelegate中以删除特定ViewController中IQKeyboardManager的工具栏。这里我的ViewController是ChatMessageViewController

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{        
    [[IQKeyboardManager sharedManager] disableToolbarInViewControllerClass:[ChatMessagesViewController class]];

    return YES;
}

现在,您可以看到textView在输入时可以增长,也可以缩小。

  

注意 - 如果您不想使用IQKeyboardManager,则必须将观察者添加为NSNotificationCenter以进行键盘显示和隐藏。喜欢这个

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
}

这两种方法清楚地写在库中,但我们也必须使用autolayout进行管理。所以最好使用IQKeyboarManager及其简单。