獲取鍵盤高度- iOS

聲明一個(gè)鍵盤高度屬性

@property (nonatomic, assign)CGSize kbSize;

在 viewDidLoad 中視圖注冊通知中心
[self registerForKeyboardNotifications];

pragma mark -- 注冊鍵盤的通知中心獲取鍵盤的高度

//注冊一個(gè)鍵盤的通知中心

 - (void)registerForKeyboardNotifications{
    
    //使用NSNotificationCenter 鍵盤出現(xiàn)時(shí)
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil];

    }

//實(shí)現(xiàn)當(dāng)鍵盤出現(xiàn)的時(shí)候計(jì)算鍵盤的高度大小。用于輸入框顯示位置

- (void)keyboardWasShown:(NSNotification*)aNotification
{
    
    NSDictionary* info = [aNotification userInfo];
    //kbSize鍵盤尺寸 (有width, height)
    self.kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;//鍵盤高度
    NSLog(@"hight_hitht:%f",self.kbSize.height);
    
    //self.view.frame = self.view.frame.size.height - self.kbSize.height;
    
    CGRect currentFrame = self.view.frame;
    CGFloat change =self.kbSize.height;
    currentFrame.origin.y = currentFrame.origin.y - change ;
    
    [UIView animateWithDuration:0.00000000001 animations:^{
        
        self.view.frame = currentFrame;
    }];
}`

// 視圖將要消失時(shí),移除通知中心
-(void)viewWillDisappear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容