鍵盤監聽KVO和自適應TextView


#import "TwoViewController.h"
#import "ReactiveCocoa.h"
#import "myTableViewCell.h"
#import "MySelectPicCollectionView.h"
#import <BlocksKit+UIKit.h>
#import "TZImagePickerController.h"
#import "UIView+WZLBadge.h"
#import "NewChange.h"
@interface TwoViewController ()<UITableViewDelegate,UITableViewDataSource,UITextViewDelegate>
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *collectionViewHeightConstraint;
@property (weak, nonatomic) IBOutlet UIButton *twoButton;
@property (weak, nonatomic) IBOutlet UITableView *tableview;
@property (weak, nonatomic) IBOutlet UIButton *imgaebutton;
@property (weak, nonatomic) IBOutlet UITextView *textview;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *height;
@property (weak, nonatomic) IBOutlet UIButton *mybutt;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *inputToolBarBottomConstraint;
@property (nonatomic,strong)NSMutableArray *dataSource;
@property (nonatomic, assign) CGFloat previousTextViewContentHeight;
@property (nonatomic, assign) CGFloat contentOffsetY;

@property (weak, nonatomic) IBOutlet MySelectPicCollectionView *myCollectView;
@property (weak, nonatomic) IBOutlet UIView *myBageView;

@end

@implementation TwoViewController
- (CGFloat)previousTextViewContentHeight {
    if (_previousTextViewContentHeight == 0) {
        _previousTextViewContentHeight = self.textview.frame.size.height;
    }
    return _previousTextViewContentHeight;
}


- (NSMutableArray *)dataSource{
    if (!_dataSource) {
        self.dataSource = [NSMutableArray arrayWithCapacity:0];
    }return _dataSource;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [_imgaebutton bk_addEventHandler:^(id sender) {
        
        [self.textview resignFirstResponder];
        
        self.collectionViewHeightConstraint.constant = 216;
        [NewChange showImagePickerFor:self phoneNum:9 videoNum:0 finishPick:^(NSArray *sourceArr, NSArray *assets) {
            [self.myCollectView configWithData:sourceArr];
            if (sourceArr.count >0) {
                [self.myBageView showBadgeWithStyle:WBadgeStyleNumber value:sourceArr.count animationType:WBadgeAnimTypeNone];

            }else{
                [self.myBageView clearBadge];
            }
            
        }];
        
    } forControlEvents:UIControlEventTouchUpInside];

    // 1.監聽鍵盤彈出,把inputToolBar(輸入工具條)往上移
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(kbWillShow:) name:UIKeyboardWillShowNotification object:nil];
    _textview.delegate = self;
    // 2.監聽鍵盤退出,inputToolBar回復原位
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(kbWillHide:) name:UIKeyboardWillHideNotification object:nil];
    [_textview setBackgroundColor: [UIColor redColor]];
    [_mybutt addTarget:self action:@selector(Sender:) forControlEvents:UIControlEventTouchUpInside];
    // 添加動畫
    [UIView animateWithDuration:0.25 animations:^{
        [self.view layoutIfNeeded];
    }];

}
- (void)Sender:(id)sender{
    [self.dataSource addObject:_textview.text];
    [self.tableview reloadData];
    // 清空textView的文字
    _textview.text = nil;
    self.height.constant = 50;
    _textview.contentSize = CGSizeMake(self.view.frame.size.width - 124, 50);
    [_textview setContentInset:UIEdgeInsetsMake(0, 0, 0, 0)];
    
}

#pragma mark 鍵盤顯示時會觸發的方法
-(void)kbWillShow:(NSNotification *)noti {
    //1.獲取鍵盤高度
    //1.1獲取鍵盤結束時候的位置
    CGRect kbEndFrame = [noti.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat kbHeight = kbEndFrame.size.height;
    
    CGRect beginRect = [[noti.userInfo objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];
    
    CGRect endRect = [[noti.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    NSLog(@"%f", kbHeight);
    // 第三方鍵盤回調三次問題,監聽僅執行最后一次
    
    if(!(beginRect.size.height > 0 && ( fabs(beginRect.origin.y - endRect.origin.y) > 0))) return;
    
    CGFloat animationDuration = [[noti.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    // 2.更改inputToolBar 底部約束
    self.inputToolBarBottomConstraint.constant = kbHeight;
    self.collectionViewHeightConstraint.constant = 0;
   
        [UIView animateWithDuration:animationDuration animations:^{
            [self.view layoutIfNeeded];
        }];
    
    // 4.把消息現在在頂部
}

#pragma mark 鍵盤退出時會觸發的方法
-(void)kbWillHide:(NSNotification *)noti{
    //inputToolbar恢復原位
    self.inputToolBarBottomConstraint.constant = 0;
    self.height.constant = 50;
    _textview.contentSize = CGSizeMake(self.view.frame.size.width - 124, 50);
    // 添加動畫
    [UIView animateWithDuration:0.25 animations:^{
        [self.view layoutIfNeeded];
    }];
}

//pragma mark - UITextView代理
-(void)textViewDidChange:(UITextView *)textView {
    // 1.計算textView的高度
    CGFloat textViewH = 0;
    CGFloat minHeight = 33 + 3; // textView最小的高度
    CGFloat maxHeight = 150 + 3 +10; // textView最大的高度
    
    // 獲取contentSize 的高度
    CGFloat contentHeight = textView.contentSize.height;
    
    if (contentHeight < minHeight) {
        textViewH = minHeight;
        [textView setContentInset:UIEdgeInsetsZero];
    } else if (contentHeight > maxHeight) {
        textViewH = maxHeight + 4.5;
        [textView setContentInset:UIEdgeInsetsMake(-5, 0, -3.5, 0)];
    } else {
        if (contentHeight ==  minHeight) {
            [textView setContentInset:UIEdgeInsetsZero];
            textViewH = minHeight;
        } else {
            textViewH = contentHeight - 8;
            [textView setContentInset:UIEdgeInsetsMake(-4.5, 0, -4.5, 0)];
        }
    }
    
   
    // 3.調整整個InputToolBar 的高度
    self.height.constant = 6 + 7 + textViewH;
    CGFloat changeH = textViewH - self.previousTextViewContentHeight;
    if (changeH != 0) {
        
        // 加個動畫
        [UIView animateWithDuration:0.25 animations:^{
            [self.view layoutIfNeeded];
            if (textView.text.length) {
            }
            // 4.記光標回到原位
            // 下面這幾行代碼需要寫在[self.view layoutIfNeeded]后面,不然系統會自動調整為位置
            if (contentHeight < maxHeight) {
                [textView setContentOffset:CGPointZero animated:YES];
                [textView scrollRangeToVisible:textView.selectedRange];
            }
        }];
        self.previousTextViewContentHeight = textViewH;
    }
    
    if (contentHeight > maxHeight) {
        [UIView animateWithDuration:0.2 animations:^{
            if (self.contentOffsetY) {
                if (textView.selectedRange.location != textView.text.length && textView.contentOffset.y != self.contentOffsetY) return;
            }
            [textView setContentOffset:CGPointMake(0.0, textView.contentSize.height - textView.frame.size.height - 3.5)];
            self.contentOffsetY = textView.contentOffset.y;
        }];
        [textView scrollRangeToVisible:textView.selectedRange];
    }
    
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.count;
}

// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    myTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"myTableViewCell" forIndexPath:indexPath];
    [cell.mytableview setText:self.dataSource[indexPath.row]];
    return cell;
}
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{
    [self.textview resignFirstResponder];
    self.collectionViewHeightConstraint.constant = 0;

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,908評論 6 541
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,324評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,018評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,675評論 1 317
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,417評論 6 412
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,783評論 1 329
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,779評論 3 446
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,960評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,522評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,267評論 3 358
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,471評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,009評論 5 363
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,698評論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,099評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,386評論 1 294
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,204評論 3 398
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,436評論 2 378

推薦閱讀更多精彩內容