在iOS開發過程當中,視圖的層次是很是重要的,每每一不當心就會形成出乎意料的bug。一般體如今button不靈敏或拖拽失效等;xcode
Xcode6出來後,有個功能叫View UI Hierarchy,即UI檢視器。它的位置在xcode中的ide
它很是的方便咱們觀察UI的位置及視圖的層次。spa
在iOS中管理視圖層次的二個重要方法就是code
//將view顯示在最前server
- (void)bringSubviewToFront:(UIView *)view;blog
例如:[self.view bringSubviewToFront:self.firstView];ip
//將view顯示在最後開發
- (void)sendSubviewToBack:(UIView *)view;get
例如:[self.view sendSubviewToBack:self.firstView];animation
在這裏我將着重講下sendSubviewToBack一個很妙的用法。
經常在處理文本框輸入內容時,一般是註冊一個通知,而後將view向上頂,
就像這樣
//註冊鍵盤通知
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification
object:nil];
而後再將界面向上頂
-(void) keyboardWillShow:(NSNotification *)note{
// get keyboard size and loctaion
CGRect keyboardBounds;
[[note.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey] getValue: &keyboardBounds];
NSNumber *duration = [note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
NSNumber *curve = [note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
// Need to translate the bounds to account for rotation.
keyboardBounds = [self.view convertRect:keyboardBounds toView:nil];
// get a rect for the textView frame
if ([self.contextView isFirstResponder]) {
CGRect containerFrame = self.creatView.frame;
containerFrame.origin.y = self.view.bounds.size.height - (keyboardBounds.size.height + containerFrame.size.height);
containerFrame.origin.x = 21;
containerFrame.size.width=278;
// animations settings
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:[duration doubleValue]];
[UIView setAnimationCurve:[curve intValue]];
// set views with new info
self.creatView.frame = containerFrame;
// commit animations
[UIView commitAnimations];
}
}
但這樣作的話會有個很差的地方,那就是可能會將自定義的導航欄頂出界面外了,就像這樣
這樣的話雖然說鍵盤並無擋住文本框的效果實現了,但界面體驗不太好。那麼該怎麼辦呢。
其實咱們分析緣由可知,之因此導航欄向上頂了,由於其所屬的層在整個view中
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{
if ([textView isKindOfClass:[self.secondview.descriptionTextView class]]) {
[self.view sendSubviewToBack:self.secondview];
[UIView animateWithDuration:0.35f animations:^{
[self.secondview setFrame:CGRectMake(self.secondview.frame.origin.x, self.secondview.frame.origin.y - 216.0f, self.secondview.frame.size.width, self.secondview.frame.size.height)];
} completion:^(BOOL finished) {
}];
}
return YES;
}
調整後,能夠看到,鍵盤彈出後,導航欄並無消失
至此,問題完美解決!