2014-10-30 3 views
1

Я очень младший мобильный программист. Мне нужно переместить текстовые представления при появлении клавиатуры. Я следую этому move-uiview-up-when-the-keyboard-appears-in-ios, и он работает хорошо, но у меня есть фоновое изображение, и я не хочу для перемещения фонового изображения. Все текстовые поля встраиваются в UIView с именем as customView. Я пытался перемещаться по customView вместо self.view. Когда я начинаю вводить в первом текстовом виде, пользовательский интерфейс перемещается вверх. Но когда я перехожу во второе текстовое представление, customview перемещается в исходное положение, а textView становится под клавиатурой. Для того, чтобы начинать вводить во втором текстовом представлении, нужно постоянно перемещаться вверх. Я действительно ценю любую помощь !.Передвиньте текстовое поле, когда клавиатура появляется в Objective C

@property (strong, nonatomic) IBOutlet UIView *customView; 
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField { 
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil]; 
return YES; } 


- (BOOL)textFieldShouldEndEditing:(UITextField *)textField { 
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHide:) name:UIKeyboardDidHideNotification object:nil]; 

[self.view endEditing:YES]; 
return YES; } 


- (void)keyboardDidShow:(NSNotification *)notification 
{ 
    //Assign new frame to your view 
    [self.customView setFrame:CGRectMake(0,50,320,460)]; 

} 

-(void)keyboardDidHide:(NSNotification *)notification 
{ 
    [self.customView setFrame:CGRectMake(0,193,320,460)]; 
} 

ответ

5

Добавить наблюдателя в поле зренияDidLoad для наилучшего подхода.

- (void)viewDidLoad { 

    [super viewDidLoad]; 

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

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHidden:) name:UIKeyboardWillHideNotification object:nil]; 

} 

- (void)keyboardWillShow:(NSNotification*)aNotification { 
    [UIView animateWithDuration:0.25 animations:^ 
    { 
     CGRect newFrame = [customView frame]; 
     newFrame.origin.y -= 50; // tweak here to adjust the moving position 
     [customView setFrame:newFrame]; 

    }completion:^(BOOL finished) 
    { 

    }]; 
} 

- (void)keyboardWillBeHidden:(NSNotification*)aNotification { 
    [UIView animateWithDuration:0.25 animations:^ 
    { 
     CGRect newFrame = [customView frame]; 
     newFrame.origin.y += 50; // tweak here to adjust the moving position 
     [customView setFrame:newFrame]; 

    }completion:^(BOOL finished) 
    { 

    }]; 

    } 

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { 
    [self.view endEditing:YES]; 
} 
+0

Он отлично работает в ios7, но он не работает в ios8.I не уверен, почему. Не могли бы вы мне помочь? – sasha

+0

Он отлично работает в iOS 8.1, не уверен в 8.0, пожалуйста, проверьте 8.1. –

+0

Спасибо. Я нашел решение для ios8 в http://stackoverflow.com/questions/26112319/ios8-whats-going-on-with-moving-views-during-keyboard-transitions. – sasha

0

Внесите свой класс в эксплуатацию UITextFieldDelegate.

Вставьте следующий код в viewDidLoad.

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

И определите следующие функции в вашем файле .m.

- (void)keyboardWasShown:(NSNotification *)aNotification 

{// scroll to the text view 
NSDictionary* info = [aNotification userInfo]; 
CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size; 

UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0); 
self.scrollView.contentInset = contentInsets; 
self.scrollView.scrollIndicatorInsets = contentInsets; 

// If active text field is hidden by keyboard, scroll it so it's visible. 
// Your app might not need or want this behavior. 
CGRect aRect = self.view.frame; 
aRect.size.height -= kbSize.height; 
self.scrollView.scrollEnabled = YES; 
if (!CGRectContainsPoint(aRect, activeField.frame.origin)) { 
    [self.scrollView scrollRectToVisible:activeField.frame animated:YES]; 
} 
} 

- (void)keyboardWillBeHidden:(NSNotification *)aNotification 
{ 
// scroll back.. 
UIEdgeInsets contentInsets = UIEdgeInsetsZero; 
self.scrollView.contentInset = contentInsets; 
self.scrollView.scrollIndicatorInsets = contentInsets; 
self.scrollView.scrollEnabled = NO; 
} 

- (void)textFieldDidBeginEditing:(UITextField *)textField 
{ 
activeField = textField; 
} 

- (void)textFieldDidEndEditing:(UITextField *)textField 
{ 
activeField = nil; 
} 
0

// Добавление Scrollview на главном экране и добавить UITextField на этой Scrollview

-(void) viewDidLoad 
{ 
    UIScrollView *myScrollView = [[UIScrollView alloc] initWithFrame:[UIScreen mainScreen].bounds]; 
    myScrollView.contentSize = CGSizeMake(320, 500); 
    myScrollView.contentInset = UIEdgeInsetsMake(0, 0, 60, 0); 
    [self.view addSubview:myScrollView]; 

    UITextField *myTextField = [[UITextField alloc] initWithFrame:CGRectMake(20,30,100,33)]; 
    [myScrollView addSubview:myTextField]; 
    myTextField.delegate = self; 
} 

// Установить содержание Scrollview смещение, чтобы сделать MyTextField двигаться вверх

- (void) textFieldDidBeginEditing:(UITextField *)textField 
{ 
[myScrollView setContentOffset:CGPointMake(0,textField.center.y-80)   animated:YES]; 
// here '80' can be any number which decide the height that textfiled  should move 
} 

// Перемещение текстового поля в исходное положение

- (BOOL) textFieldShouldReturn:(UITextField *)textField 
{ 
    [[myScrollView setContentOffset:CGPointMake(0,0) animated:YES]; 
    [textField resignFirstResponder]; 
    return YES; 
} 
Смежные вопросы