你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> 學習iOS自定義導航控制器UINavigationController

學習iOS自定義導航控制器UINavigationController

編輯:IOS開發綜合

自定義導航控制器: 將導航控制器中通用的部分拿出來統一設置

1、一般導航條標題的字體setTitleTextAttribute和背景顏色setBackgroundImage都是統一的,可以在load方法中使用appearanceWhenContainedIn統一設置
2、一般導航條的返回按鈕需要自定義,一般除了棧底控制器有導航條,其他控制器都需要隱藏底部的條,可以重寫pushViewController:animated:方法,在該方法中實現該功能
3、導航控制器右滑返回效果(觸摸屏幕的任意一點,向右滑動返回)

UIViewController 
 --navigationItem 
   leftBarButtonItem | leftBarButtonItems
   NSString title | UIView titleView
   rightBarButtonItem | rightBarButtonItems
   backBarButtonItem

#import "BWNavigationController.h"
#import "UIBarButtonItem+Item.h"

@interface BaseNavigationController () <UIGestureRecognizerDelegate>

@end

@implementation BWNavigationController

+ (void)load {
  [super load];
  UINavigationBar *navigationBar = [UINavigationBar appearanceWhenContainedIn:self, nil];

  NSMutableDictionary *dict = [NSMutableDictionary dictionary];
  dict[NSFontAttributeName] = [UIFont boldSystemFontOfSize:20];
  [navigationBar setTitleTextAttributes:dict];

  [navigationBar setBackgroundImage:[UIImage imageNamed:@"navigationbarBackgroundWhite"] forBarMetrics:UIBarMetricsDefault];
}

- (void)viewDidLoad {
  [super viewDidLoad];
  // 屏幕邊緣滑動(只能在屏幕的邊緣才能觸發該手勢,不能在屏幕的任意一點觸發該手勢)
  UIScreenEdgePanGestureRecognizer *edgePanGestureRecognizer = (UIScreenEdgePanGestureRecognizer *)self.interactivePopGestureRecognizer;

  // 滑動手勢(禁用系統自帶的屏幕邊緣滑動手勢,使用自定義的滑動手勢目的就是達到觸摸屏幕上的任意一點向右滑動都能實現返回的效果)
  UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:edgePanGestureRecognizer.delegate action:@selector(handleNavigationTransition:)];
  panGestureRecognizer.delegate = self;
  [self.view addGestureRecognizer:panGestureRecognizer];

  // 禁用系統的屏幕邊緣滑動手勢
  edgePanGestureRecognizer.enabled = NO;
}

// 是否允許觸發手勢,如果是根視圖控制器則不需要
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
  return self.childViewControllers.count > 1;
}

- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated {
  // 統一設置返回按鈕
  NSInteger count = self.childViewControllers.count;
  if (count > 0) {
    viewController.hidesBottomBarWhenPushed = YES;
    viewController.navigationItem.leftBarButtonItem = [UIBarButtonItem backBarButtonItemWithImage:[UIImage imageNamed:@"navigationButtonReturn"] highlightImage:[UIImage imageNamed:@"navigationButtonReturnClick"] tagert:self action:@selector(back) title:@"返回"];
  }

  [super pushViewController:viewController animated:animated];
}

- (void)back {
  [self popViewControllerAnimated:YES];
}
@end

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持本站。

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved