2015-01-16 155 views
2

我想在出現鍵盤時調整文本視圖的大小。我的代碼如下。我有自動佈局,因此使用superview中的textView->底部空間約束,並通過IBOutlet distanceFromBottom引用它。當出現鍵盤時調整UITextView的大小

- (void)keyboardWillShow:(NSNotification *)notification 
{ 
    [UIView animateWithDuration:0.3 animations:^{ 
    NSDictionary* d = [notification userInfo]; 
    CGRect r = [d[UIKeyboardFrameEndUserInfoKey] CGRectValue]; 
    r = [textView convertRect:r fromView:Nil]; 
    if(IS_IPHONE_6||IS_IPHONE_6P) 
     distanceFromBottom.constant = r.origin.y+78; 
    else if(IS_IPHONE_5) 
     distanceFromBottom.constant = r.origin.y+183; 
    }]; 
} 

上面的代碼工作完美。我不明白的是爲什麼我需要爲iPhone6添加+78或爲iPhone5添加183。這兩個價值觀我帶着試驗和錯誤。如果我不添加這些,textView會延伸到鍵盤下方。請幫我解決這個謎。

回答

9

viewWillAppear方法中,添加以下:

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

    [[NSNotificationCenter defaultCenter] 
     addObserver:self 
      selector:@selector(handleKeyboardDidShow:) 
       name:UIKeyboardDidShowNotification object:nil]; 

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

然後實現通知中心的兩種方法,這樣的:

- (void) handleKeyboardDidShow:(NSNotification *)paramNotification{ 

    NSValue *keyboardRectAsObject = 
     [[paramNotification userInfo] 
      objectForKey:UIKeyboardFrameEndUserInfoKey]; 

    CGRect keyboardRect = CGRectZero; 
    [keyboardRectAsObject getValue:&keyboardRect]; 

    yourTextView.contentInset = 
     UIEdgeInsetsMake(0.0f, 
         0.0f, 
         keyboardRect.size.height, 
         0.0f); 
} 

而另外一個這樣的:

- (void) handleKeyboardWillHide:(NSNotification *)paramNotification{ 

    yourTextView.contentInset = UIEdgeInsetsZero; 
} 

它適用於所有設備;)

+1

真棒先生。像魅力一樣工作。 :) – user1191140

4

夫特/修改版本

使用上面,我做了一些調整使用NSLayoutConstraint的改變高度constant屬性當鍵盤顯示和隱藏。這也適用於旋轉設備。

1.設置TextView的約束

然後拖動控制的電源插座你高度約束的類。

enter image description here

2.添加以下

override func viewWillAppear(animated: Bool) { 
     super.viewWillAppear(animated) 

     NSNotificationCenter.defaultCenter().addObserver(self, selector:#selector(SkillDescriptionViewController.keyboardWillShowHandle(_:)), name: UIKeyboardDidShowNotification, object: nil) 

     NSNotificationCenter.defaultCenter().addObserver(self, selector:#selector(SkillDescriptionViewController.keyboardWillHideHandle), name: UIKeyboardWillHideNotification, object: nil) 

    } 


    func keyboardWillShowHandle(note:NSNotification) { 
     guard let keyboardRect = note.userInfo![UIKeyboardFrameEndUserInfoKey] as? NSValue else { return } 
     let kbFrame = keyboardRect.CGRectValue() 
     tvHeight.constant = -kbFrame.height 
     view.layoutIfNeeded() 
    } 

    func keyboardWillHideHandle() { 
     tvHeight.constant = 0 
     view.layoutIfNeeded() 
    } 
相關問題