0
當鍵盤覆蓋文本框時,我使用代碼使屏幕滾動。iOS - 鍵盤上的UIScroll在文本框位於子視圖內時彈出到文本框
我有一個文本框的列表,我開始把每個內部的自己的uiview用於樣式和組織目的。
現在我的代碼只適用於當我開始實際輸入文本字段。這是我從蘋果複製的怪物。注:我加一個參數 registerForKeyboardNotifications,這樣我可以包括這在父類和從任何地方
// Call this method somewhere in your view controller setup code.
- (void)registerForKeyboardNotifications:(UIScrollView *)scroll
{
_scroller = scroll;
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWasShown:)
name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillBeHidden:)
name:UIKeyboardWillHideNotification object:nil];
}
// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification
{
NSLog(@"hey");
NSDictionary* info = [aNotification userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
_scroller.contentInset = contentInsets;
_scroller.scrollIndicatorInsets = contentInsets;
// If active text field is hidden by keyboard, scroll it so it's visible
// Your application might not need or want this behavior.
CGRect aRect = self.view.frame;
aRect.size.height -= kbSize.height;
if (!CGRectContainsPoint(aRect, _activeField.frame.origin)) {
CGPoint scrollPoint = CGPointMake(0.0, _activeField.frame.origin.y-kbSize.height);
[_scroller setContentOffset:scrollPoint animated:YES];
}
}
// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
UIEdgeInsets contentInsets = UIEdgeInsetsZero;
_scroller.contentInset = contentInsets;
_scroller.scrollIndicatorInsets = contentInsets;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField{
_activeField = textField;
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
_activeField = nil;
}
我在視圖 - 控制
for (id subView in _tpnScroll.subviews)
{
if ([subView isKindOfClass:[UIView class]]) {
UIView *thisView = subView;
for(id textfield in thisView.subviews){
if([textfield isKindOfClass:[UITextField class]]){
[textfield setDelegate:self];
}
}
}
}
縮小問題這部分稱之爲原始代碼是
for (id subView in _tpnScroll.subviews){
if ([subView isKindOfClass:[UITextField class]]) {
[subView setDelegate:self];
}
}
在第一個例子中。我循環通過我的UIViews,並找到UITextfields,並設置委託給自己(這部分我不完全理解,仍試圖理解委託的概念)
在第二個示例中,文本字段位於直接在scrollview上,所以我直接通過它們循環。
對不起,如果這是羅嗦。
這沒有工作。我不確定你瞭解我的結構。我有一個視圖 - >滾動視圖 - >許多視圖 - >很多文本字段 這是工作正常時,它是視圖 - > scrollview - >文本字段 – hamobi
@hamobi我瞭解結構。原始代碼的問題在於,您在包含它們的視圖中的文本字段的框架不在滾動視圖的座標中。 你在哪裏設置內容大小?另外,確保正在調用textFieldDidBeginEditing:。 –
該方法被稱爲 我注意到這個值_activeField.frame.origin.y-kbSize.height 結束爲一個負數。這可能是什麼原因造成的。我怎麼能得到相對於滾動視圖的文本框的座標而不是坐在它的uiview? – hamobi