iOS 实现一个最简单的文本聊天框(自动根据内容改变高度)

2018-01-30  本文已影响148人  JohnayXiao
IMG_4719.PNG IMG_4720.PNG

.h文件

#import <UIKit/UIKit.h>

@protocol XJAutoHeightInputTextViewDelegate <NSObject>

@optional
- (void)postBtnClick:(UITextView *)textView complection:(void(^)(BOOL isDone))complectionBlock;

@end

@interface XJAutoHeightInputTextView : UIView

@property (nonatomic,strong)id <XJAutoHeightInputTextViewDelegate> delegate;

-(instancetype)initWithDelegate:(id)delegate;

@end

.m文件

#import "XJAutoHeightInputTextView.h"

//所有的宏在这里,自行删除
#define XJ_ScreenWidth   [UIScreen mainScreen].bounds.size.width
#define XJ_ScreenHeight  [UIScreen mainScreen].bounds.size.height

// iPhone X
#define  XJ_iPhoneX (XJ_ScreenWidth == 375.f && XJ_ScreenHeight == 812.f ? YES : NO)

#define XJ_StatusBarHeight (XJ_iPhoneX ? 44.f : 20.f)
#define XJ_NavigationBarHeight  (XJ_iPhoneX ? 88.f : 64.f)
#define XJ_TabbarHeight         (XJ_iPhoneX ? (49.f+34.f) : 49.f)
#define XJ_safeBottomMargin   (XJ_iPhoneX ? 34.f : 0.f)


@interface XJAutoHeightInputTextView()<UITextViewDelegate>
@property (nonatomic,weak)UITextView * textView;
/**总共字数*/
@property (nonatomic,weak)UILabel * numberLable;
/**默认提示语*/
@property (nonatomic,weak)UILabel * apleLable;
@property (nonatomic,strong)UILabel *sendLable;
@property (nonatomic, assign) CGRect keyBordFrame;

@end


@implementation XJAutoHeightInputTextView

-(instancetype)initWithDelegate:(id)delegate
{
    if (self = [super init])
    {
        self.delegate = delegate;
        self.frame = CGRectMake(0, XJ_ScreenHeight - XJ_TabbarHeight, XJ_ScreenWidth, 49);
        self.backgroundColor = [UIColor whiteColor];
        UITextView * textView = [[UITextView alloc] initWithFrame:CGRectMake(15, 4.5, self.bounds.size.width/1.3, 40)];
        self.textView = textView;
        //颜色自行设置啊。。。
        //        textView.backgroundColor = grayBgColor();
        textView.layer.cornerRadius = textView.frame.size.height / 2.0;
        textView.layer.masksToBounds = YES;
        textView.delegate = self;
        textView.scrollEnabled=  NO;
        textView.keyboardType = UIKeyboardTypeDefault;
        textView.returnKeyType = UIReturnKeySend;
        textView.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
        textView.font=[UIFont fontWithName:@"Arial" size:18.0];
        textView.textAlignment = NSTextAlignmentLeft;
        //        textView.textColor = [UIColor colorWithHexString:@"5d6573"];
        textView.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;;
        
        [self addSubview:textView];
        UILabel * apleLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, textView.frame.origin.y-2, textView.bounds.size.width-30, textView.bounds.size.height)];
        apleLabel.text = @" 请输入评论";
        apleLabel.textAlignment = NSTextAlignmentLeft;
        apleLabel.textColor = [UIColor colorWithRed:170/255.0 green:170/255.0 blue:170/255.0 alpha:0.8];
        apleLabel.font = [UIFont fontWithName:@"Arial" size:17.0];
        self.apleLable = apleLabel;
        [self addSubview:apleLabel];
        
        UILabel * sendLable = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(textView.frame) , 4.5, 60, 40)];
        sendLable.textAlignment = NSTextAlignmentCenter;
        sendLable.text = @"发送";
        //        sendLable.textColor = grayDarkTextColor();
        sendLable.font = [UIFont fontWithName:@"Arial" size:16.0];
        sendLable.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(done)];
        [sendLable addGestureRecognizer:tap];
        self.sendLable = sendLable;
        [self addSubview:sendLable];
        
        UILabel * numberLable = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(textView.frame), (self.bounds.size.height - 40), 60, 20)];
        numberLable.textAlignment = NSTextAlignmentCenter;
        numberLable.textColor = [UIColor colorWithRed:170/255.0 green:170/255.0 blue:170/255.0 alpha:1];
        numberLable.text = @"140/140";
        numberLable.font = [UIFont fontWithName:@"Arial" size:12.0];
        self.numberLable = numberLable;
        [self addSubview:numberLable];
        numberLable.hidden = YES;
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChanged:) name:UITextViewTextDidChangeNotification object:nil];
    }
    return self;
}

/**键盘出现*/
- (void)keyboardWillShow:(NSNotification*)notification
{
    CGRect keyboardRect = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    self.keyBordFrame = keyboardRect;
    
    [UIView animateWithDuration:0.3 animations:^{
        
        self.frame = CGRectMake(0, XJ_ScreenHeight - keyboardRect.size.height - self.bounds.size.height, XJ_ScreenWidth, self.bounds.size.height);
        
    }];
    
}
/**键盘下落*/
- (void)keyboardWillHide:(NSNotification*)notification
{
    [UIView animateWithDuration:0.38 animations:^{
        
        self.frame = CGRectMake(0, XJ_ScreenHeight - self.bounds.size.height - XJ_safeBottomMargin, XJ_ScreenWidth, self.bounds.size.height);
        
    }completion:^(BOOL finished) {
        
    }];
}


-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"]) {
        
        [self done];
        return YES;
        
    } else{
        
        NSString *new = [textView.text stringByReplacingCharactersInRange:range withString:text];
        
        if (new.length) {
            
            self.apleLable.hidden = YES;
            
        }else{
            
            self.apleLable.hidden = NO;
        }
        
        NSInteger lenth= [new length];
        if (lenth >140)
        {
            return NO;
            
        }else{
            
            NSInteger numb = 140 - lenth;
            self.numberLable.text = [NSString stringWithFormat:@"%ld/140",numb];
        }
        
        NSInteger res = 140-[new length];
        
        if(res >= 0)
        {
            return YES;
            
        }else{
            
            NSRange rg = {0,[text length]+res};
            
            if (rg.length>0) {
                
                NSString *s = [text substringWithRange:rg];
                [textView setText:[textView.text stringByReplacingCharactersInRange:range withString:s]];
            }
            return NO;
        }
    }
}

/**监听文字改变 换行时要更改输入框的位置*/
- (void)textDidChanged:(NSNotification *)notif
{
    static CGFloat maxHeight = 40.0f;
    CGRect frame = self.textView.frame;
    CGSize constraintSize = CGSizeMake(frame.size.width, MAXFLOAT);
    CGSize size = [self.textView sizeThatFits:constraintSize];
    maxHeight = size.height <= 40 ? 40 : size.height;
    CGFloat heightSelf = maxHeight + 9;
    
    [UIView animateWithDuration:0.38 animations:^{
        
        self.frame = CGRectMake(0, XJ_ScreenHeight - self.keyBordFrame.size.height - heightSelf, XJ_ScreenWidth, heightSelf);
        
        self.textView.frame = CGRectMake(15, 4.5, frame.size.width, maxHeight);
        
        self.sendLable.frame = CGRectMake(CGRectGetMaxX(self.textView.frame), (self.bounds.size.height - 44.5), 60, 40);
        
        if (maxHeight <= 40) {
            
            self.numberLable.hidden = YES;
            
        } else self.numberLable.hidden = NO;
    }];
}

//发送
- (void)done
{
    [self.textView resignFirstResponder];
    
    if ([self.delegate respondsToSelector:@selector(postBtnClick:complection:)]) {
        
        [self.delegate postBtnClick:self.textView complection:^(BOOL isDone) {
            
            [self.textView resignFirstResponder];
            self.frame = CGRectMake(0, XJ_ScreenHeight - XJ_TabbarHeight, XJ_ScreenWidth, 49);
            
            self.textView.frame = CGRectMake(15, 4.5, self.bounds.size.width/1.3, 40);
            
            self.sendLable.frame = CGRectMake(CGRectGetMaxX(self.textView.frame), 4.5, 60, 40);
            self.textView.text = @" ";
            self.apleLable.hidden = NO;
            self.numberLable.text = @"140";
            self.numberLable.hidden = YES;
        }];
    }
}


#pragma mark - setter
-(void)dealloc //移除通知
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextViewTextDidChangeNotification object:nil];
}

@end



上一篇下一篇

猜你喜欢

热点阅读