有關鍵盤出現時移動UITableView
的許多答案,但我的問題是不同的。我可以在出現鍵盤時移動UITableView
,但是我面臨的唯一問題是當我第一次訪問視圖時,不會滾動,但是當我按回按鈕並重新訪問視圖時,它的工作正常。我很困惑這是每次都期望我第一次訪問視圖時使用的相同代碼。我在xib中使用UITableView。我嘗試設置contentInset但沒用。任何幫助將非常感激。當第一次啓動視圖時出現鍵盤時,uitableview不會滾動。後來它正常工作
我張貼這說明我面臨
問題的圖像下面是我的代碼。
- (void)viewDidLoad
{
[super viewDidLoad];
//keyboard observers
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
//tap on tableview or whole view
UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
[self.view addGestureRecognizer:gestureRecognizer];
//scroll to bottom of conversation
[self scrollToBottomOfConversation];
}
- (void)scrollToBottomOfConversation
{
CGFloat yOffset = 0;
if (_chatConversationTableView.contentSize.height > _chatConversationTableView.bounds.size.height) {
yOffset = _chatConversationTableView.contentSize.height - _chatConversationTableView.bounds.size.height;
}
[_chatConversationTableView setContentOffset:CGPointMake(0, yOffset) animated:NO];
}
- (void)keyboardWillShow:(NSNotification *)notification
{
NSDictionary *userInfo = [notification userInfo];
CGSize size = [[userInfo objectForKey: UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
CGRect frame = CGRectMake(_chatConversationTableView.frame.origin.x,
_chatConversationTableView.frame.origin.y,
_chatConversationTableView.frame.size.width,
_chatConversationTableView.frame.size.height - size.height);
_chatConversationTableView.frame = frame;
CGRect framee = containerView.frame;//containerView is my subView which holds the textbox and send button
framee.origin.y = self.view.frame.size.height - framee.size.height - size.height;
containerView.frame = framee;
[UIView commitAnimations];
//scroll to bottom of conversation
[self scrollToBottomOfConversation];
}
-(void)keyboardWillHide:(NSNotification *)notification
{
NSDictionary *userInfo = [notification userInfo];
CGSize size = [[userInfo objectForKey: UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
_chatConversationTableView.frame = CGRectMake(_chatConversationTableView.frame.origin.x,
_chatConversationTableView.frame.origin.y,
_chatConversationTableView.frame.size.width,
_chatConversationTableView.frame.size.height + size.height);
CGRect frame = containerView.frame;
frame.origin.y = self.view.frame.size.height - frame.size.height;
containerView.frame = frame;
[UIView commitAnimations];
}
在viewDidAppear方法中寫入「[self scrollToBottomOfConversation]」,而不是viewDidLoad方法。 –
@yagneshdobariya我已經嘗試過,但沒有用。 – Madhu
當鍵盤出現時,由於鍵盤隱藏表,所以更改了表格的底部約束... –