iOS開發——使用Autolayout彈出鍵盤

來源:互聯網
上載者:User

標籤:

參考:

http://segmentfault.com/q/1010000002420050

http://blog.csdn.net/qq448631961/article/details/40345653

 

思路:

在整個View下面塞進一個高度為0的視圖(使用低優先順序約束),當鍵盤改變時改變該View的高度即可。

 

constraint 有一個唯一可以修改的屬性 constant,我承認它的名字確實很具有迷惑性。。。
以題主提到的高度問題為例,可以儲存這個高度 constraint 的引用,在鍵盤出現和收合時

- (void)keyboardDidShowNotification
{
    self.viewHeightConstraint.constant = 100.f;
    [self.myView layoutIfNeed];
}

- (void)keyboardDidHideNotification
{
    self.viewHeightConstraint.constant = 300.f;
    [self.myView layoutIfNeed];
}

 

 

My Code:

註冊通知:

   1:   [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillChangeFrameNotification object:nil];

 

 

約束

@property (nonatomic,strong) NSLayoutConstraint* keyboardConstraint;

 

初始為0

   1:  self.keyboardConstraint = [NSLayoutConstraint constraintWithItem:self.keyboardView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:0];

 

 

   1:  - (void)keyboardWillShow:(NSNotification *)notification{
   2:      CGRect kbFrame = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
   3:      self.keyboardConstraint.constant = kbFrame.size.height;
   4:      [self.view addConstraint:self.keyboardConstraint];
   5:      //    [self.inputView needsUpdateConstraints];
   6:      [self.view setNeedsLayout];
   7:      [self.view layoutIfNeeded];
   8:      if (self.messages.count > 0){
   9:      NSIndexPath *idxP = [NSIndexPath indexPathForRow:(self.messages.count - 1) inSection:0];
  10:          [self.tableView scrollToRowAtIndexPath:idxP atScrollPosition:UITableViewScrollPositionBottom animated:YES];}
  11:      
  12:  }
  13:   
  14:  - (void)keyboardWillHidden{
  15:      
  16:      [self.view endEditing:YES];
  17:      [UIView animateWithDuration:0.25 animations:^{
  18:          //        self.keyboardConstraint.constant = 0;
  19:          self.keyboardConstraint.constant = 0;
  20:          //        [self.view removeConstraint:self.keyboardConstraint];
  21:          [self.view setNeedsLayout];
  22:          [self.view layoutIfNeeded];
  23:      }];
  24:      
  25:  }

iOS開發——使用Autolayout彈出鍵盤

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.