2013-04-11 23 views
0

我有一個UITextView我正在使用NSLayoutConstraint來躲閃鍵盤。這裏的約束:在UITextView上使用NSLayoutConstraint將contentSize重置爲{0,0}

self.textViewBottomConstraint = [NSLayoutConstraint constraintWithItem:textView 
                attribute:NSLayoutAttributeBottom 
                relatedBy:NSLayoutRelationEqual 
                 toItem:self.view 
                attribute:NSLayoutAttributeBottom 
                multiplier:1.0 
                constant:0.0]; 
[self.view addConstraint:self.textViewBottomConstraint]; 

當鍵盤顯示/隱藏我通過設置約束不斷鍵盤高度動畫的約束。但是,出於某種原因這樣做會將contentSize重置爲{0,0},從而打破滾動。我已經添加了一個入侵到handleKeyboardDidHide:重置內容大小爲重置前,但這有一些醜陋的副作用,如滾動位置被重置和視圖不滾動到光標位置,直到打字開始。

- (void) handleKeyboardDidShow:(NSNotification *)notification 
{ 
    CGFloat height = [KeyboardObserver sharedInstance].keyboardFrame.size.height; 
    self.textView.constant = -height; 
    [self.view layoutIfNeeded]; 
} 

- (void) handleKeyboardDidHide:(NSNotification *)notification 
{ 
    // for some reason, setting the bottom constraint resets the contentSize to {0,0}... 
    // so let's save it before and reset it after. 
    // HACK 
    CGSize size = self.textView.contentSize; 
    self.textView.constant = 0.0; 
    [self.view layoutIfNeeded]; 
    self.textView.contentSize = size; 
} 

任何人都知道如何避免這個問題呢?

+0

聽起來也許你有從頂部成爲制約上海華頂以及。如果是這樣,你想擺脫它,但有一個明確的高度設置爲文本視圖。 – rdelmar

+0

@rdelmar爲什麼頂級約束會以任何方式影響contentSize?在任何情況下,刪除頂部約束都意味着爲此視圖控制器完全拋出自動佈局。 – memmons

+0

因爲如果您有頂部約束,並且將底部移動到頂部的位置,那麼滿足約束的唯一方法就是使頂部的高度爲0。 – rdelmar

回答

1

我不知道你的代碼有什麼問題,如果你願意,我們可以詳細處理。但作爲一個初始建議,如果可能的話,不調整的UITextView:只是改變其內容和滾動插圖,就像這樣:

- (void) keyboardShow: (NSNotification*) n { 
    NSDictionary* d = [n userInfo]; 
    CGRect r = [d[UIKeyboardFrameEndUserInfoKey] CGRectValue]; 
    self.tv.contentInset = UIEdgeInsetsMake(0,0,r.size.height,0); 
    self.tv.scrollIndicatorInsets = UIEdgeInsetsMake(0,0,r.size.height,0); 
} 

即使如此,我發現,你必須要等到鍵盤隱藏動畫完成重置這些值之前:

- (void) keyboardHide: (NSNotification*) n { 
    NSDictionary* d = [n userInfo]; 
    NSNumber* curve = d[UIKeyboardAnimationCurveUserInfoKey]; 
    NSNumber* duration = d[UIKeyboardAnimationDurationUserInfoKey]; 
    [UIView animateWithDuration:duration.floatValue delay:0 
         options:curve.integerValue << 16 
        animations: 
    ^{ 
     [self.tv setContentOffset:CGPointZero]; 
    } completion:^(BOOL finished) { 
     self.tv.contentInset = UIEdgeInsetsZero; 
     self.tv.scrollIndicatorInsets = UIEdgeInsetsZero; 
    }]; 
} 

(這可能是因爲這招可以幫助你的代碼以某種方式爲好。)

相關問題