2013-02-09 36 views
7

UITextView là chế độ xem phụ của chế độ xem bộ điều khiển phương thức. Tôi cần phải giảm chiều cao UITextView khi bàn phím xuất hiện để toạ độ y dưới của đường viền của UITextView bằng tọa độ y trên cùng của bàn phím. Tôi đang đặt chiều cao bàn phímUIModalPresentationFormSheet trên iPad. Cách điều chỉnh chiều cao UITextView khi bàn phím xuất hiện

CGRect frameBegin = [[notification.userInfo objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue] ; 
CGRect frameEnd = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue]; 

CGRect resultBegin = [self.view convertRect:frameBegin fromView:nil]; 
CGRect resultEnd = [self.view convertRect:frameEnd fromView:nil]; 

CGFloat kbdHeight = resultBegin.origin.y - resultEnd.origin.y; 

Vấn đề là chế độ xem này sẽ tăng khi bàn phím xuất hiện. Làm thế nào để tính toán phối hợp đường biên trên cùng của bàn phím trong trường hợp này?

Trả lời

4

Bạn có thể làm điều này:

1. Register for keyboard notifications: 

[[NSNotificationCenter defaultCenter] addObserver:self 
             selector:@selector(myTextViewHeightAdjustMethod:) 
              name:UIKeyboardWillShowNotification 
              object:nil]; 

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

2. Calculate intersection and adjust textView height with the bottom constraint 

    - (void)myTextViewHeightAdjustMethod:(NSNotification *)notification 
    { 
     NSDictionary *userInfo = [notification userInfo]; 
     CGRect keyboardFinalFrame = [[userInfo emf_ObjectOrNilForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue]; 

     CGPoint keyboardOriginInView = [self.view convertPoint:keyboardFinalFrame.origin fromView:nil]; 

      CGFloat intersectionY = CGRectGetMaxY(self.view.frame) - keyboardOriginInView.y; 

      if (intersectionY >= 0) 
      { 
       self.textViewBottomConstraint.constant = intersectionY + originalTextViewBottomConstraint; 

       [self.textView setNeedsLayout]; 
    } 

Ghi unregister để thông báo.

+0

Rất nhiều điều đã xảy ra kể từ khi tôi tạo câu hỏi. Dù sao cảm ơn cho câu trả lời. – Michael

0

Nếu bạn không cần phải viết mã cho điều này bản thân tôi khuyên bạn nên sử dụng https://github.com/hackiftekhar/IQKeyboardManager

Nó hoạt động tuyệt vời (đối với tôi, cho đến nay) và tất cả các bạn cần làm là nhập nó và thêm một dòng này của mã trong AppDelegate:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { 

    //Magic one-liner 
    IQKeyboardManager.sharedManager().enable = true 

    return true 
} 
Các vấn đề liên quan