ios鍵盤遮擋UITextField問題


在init方法里注冊這兩個通知

    [[NSNotificationCenter defaultCenter] addObserver:selfselector:@selector(keyboardwasShown:) name:UIKeyboardDidShowNotificationobject:nil];

    [[NSNotificationCenter defaultCenter] addObserver:selfselector:@selector(keyboardwasHidden:) name:UIKeyboardDidHideNotificationobject:nil];

別忘了在dealloc里移除通知中心

    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardDidHideNotification object:nil];

下面是通知調用的兩個方法,這里的兩個通知中心只需要注冊,不需要發送消息。

-(void)keyboardwasShown:(NSNotification *) notify{
    
    NSTimeInterval animationDuration = 0.15f;
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:animationDuration];
    [UIView setAnimationCurve:UIViewAnimationCurveLinear];

    
    CGRect frame = self.frame;
        
    
    frame.origin.y -=216;//216是iphone鍵盤高,ipad是352,也可以自定義上移的高度
    
    frame.size.height +=216;
    
    self.frame = frame;
    [UIView commitAnimations];
    
}

-(void) keyboardwasHidden:(NSNotification *) notify{
    if (height == 0) {
        return ;
    }else{
    NSTimeInterval animationDuration = 0.15f;
    
    [UIView beginAnimations:nil context:nil];
    
    [UIView setAnimationDuration:animationDuration];
    
    [UIView setAnimationCurve:UIViewAnimationCurveLinear];
    CGRect frame = self.frame;
        
    frame.origin.y +=216;
        
    frame.size.height -=216;
 
    self.frame = frame;

    [UIView commitAnimations];
        height = 0;
    }
}

下面這個代理方法在編輯的時候觸發

- (void)textFieldDidBeginEditing:(UITextField *)textField{
        NSlog(@"執行了");
}

或者直接用Xib連線也能觸發。

下面再介紹一種方便的方法,先鋪一個scrollview,在它上面放UITextField,不過要注意,連線的時候要把Editing Did Begin和Editing Did End連到同兩個方法上,這樣當開始編輯和結束編輯的時候可觸發兩個不同的方法

下面是這兩個方法的實現

- (IBAction)userNameDidBegin:(id)sender {
//這里添加了一個滾動的動畫 [UIView beginAnimations:nil context:nil]; [UIView setAnimationDuration:
0.15]; //開始編輯的時候,讓_scrollView滾到CGPointMake(0, 216); CGPoint offset = CGPointMake(0, 216); [_scrollView setContentOffset:offset animated:YES]; [UIView commitAnimations]; } - (IBAction)tapInputUserName:(id)sender { [UIView beginAnimations:nil context:nil]; [UIView setAnimationDuration:0.15]; //結束編輯的時候,讓_scrollView滾到CGPointMake(0, 0); CGPoint offset = CGPointMake(0, 0); [_scrollView setContentOffset:offset animated:YES]; [UIView commitAnimations]; }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM