iOS开发tabBarViewController使用

释放双眼,带上耳机,听听看~!

iOS开发tabBarViewController使用

NS_ASSUME_NONNULL_BEGIN

@class UIView, UIImage, UINavigationController, UITabBarItem;
@protocol UITabBarControllerDelegate;

NS_CLASS_AVAILABLE_IOS(2_0) @interface UITabBarController : UIViewController <UITabBarDelegate, NSCoding>
//用于将控制器添加到导航控制器(属性)
@property(nullable, nonatomic,copy) NSArray<__kindof UIViewController *> *viewControllers;
// If the number of view controllers is greater than the number displayable by a tab bar, a "More" navigation controller will automatically be shown.
// The "More" navigation controller will not be returned by -viewControllers, but it may be returned by -selectedViewController.

//将控制器添加到导航控制器的方法
- (void)setViewControllers:(NSArray<__kindof UIViewController *> * __nullable)viewControllers animated:(BOOL)animated;
//这可能会返回“更多”导航控制器如果它存在。
@property(nullable, nonatomic, assign) __kindof UIViewController *selectedViewController; // This may return the "More" navigation controller if it exists.
//点击下标
@property(nonatomic) NSUInteger selectedIndex;
//更多的导航控制器
@property(nonatomic, readonly) UINavigationController *moreNavigationController __TVOS_PROHIBITED; // Returns the "More" navigation controller, creating it if it does not already exist.
@property(nullable, nonatomic, copy) NSArray<__kindof UIViewController *> *customizableViewControllers __TVOS_PROHIBITED; // If non-nil, then the "More" view will include an "Edit" button that displays customization UI for the specified controllers. By default, all view controllers are customizable.
//提供-[UIActionSheet showFromTabBar:]。试图修改标签栏的内容将直接抛出异常。
@property(nonatomic,readonly) UITabBar *tabBar NS_AVAILABLE_IOS(3_0); // Provided for -[UIActionSheet showFromTabBar:]. Attempting to modify the contents of the tab bar directly will throw an exception.
@property(nullable, nonatomic,weak) id<UITabBarControllerDelegate> delegate;

@end

@protocol UITabBarControllerDelegate <NSObject>
@optional
//再某种条件下跳转到控制器
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController NS_AVAILABLE_IOS(3_0);
//点击某个tabBar之后,调用的方法(常常用于更改一键多功能的tabBar)
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController;
- (void)tabBarController:(UITabBarController *)tabBarController willBeginCustomizingViewControllers:(NSArray<__kindof UIViewController *> *)viewControllers NS_AVAILABLE_IOS(3_0) __TVOS_PROHIBITED;
- (void)tabBarController:(UITabBarController *)tabBarController willEndCustomizingViewControllers:(NSArray<__kindof UIViewController *> *)viewControllers changed:(BOOL)changed NS_AVAILABLE_IOS(3_0) __TVOS_PROHIBITED;
- (void)tabBarController:(UITabBarController *)tabBarController didEndCustomizingViewControllers:(NSArray<__kindof UIViewController *> *)viewControllers changed:(BOOL)changed __TVOS_PROHIBITED;

- (UIInterfaceOrientationMask)tabBarControllerSupportedInterfaceOrientations:(UITabBarController *)tabBarController NS_AVAILABLE_IOS(7_0) __TVOS_PROHIBITED;
- (UIInterfaceOrientation)tabBarControllerPreferredInterfaceOrientationForPresentation:(UITabBarController *)tabBarController NS_AVAILABLE_IOS(7_0) __TVOS_PROHIBITED;

- (nullable id <UIViewControllerInteractiveTransitioning>)tabBarController:(UITabBarController *)tabBarController
                      interactionControllerForAnimationController: (id <UIViewControllerAnimatedTransitioning>)animationController NS_AVAILABLE_IOS(7_0);

- (nullable id <UIViewControllerAnimatedTransitioning>)tabBarController:(UITabBarController *)tabBarController
            animationControllerForTransitionFromViewController:(UIViewController *)fromVC
                                              toViewController:(UIViewController *)toVC  NS_AVAILABLE_IOS(7_0);

@end

@interface UIViewController (UITabBarControllerItem)

@property(null_resettable, nonatomic, strong) UITabBarItem *tabBarItem; // Automatically created lazily with the view controller's title if it's not set explicitly.

@property(nullable, nonatomic, readonly, strong) UITabBarController *tabBarController; // If the view controller has a tab bar controller as its ancestor, return it. Returns nil otherwise.

@end

NS_ASSUME_NONNULL_END

UItabBar

#import <Foundation/Foundation.h>
#import <UIKit/UIKitDefines.h>
#import <UIKit/UIControl.h>
NS_ASSUME_NONNULL_BEGIN
typedef NS_ENUM(NSInteger, UITabBarItemPositioning) {
//指定自动标签栏项目定位根据习语的用户界面,如下:为iPhone用户界面成语,标签栏项目填补水平标签栏,根据需要调整项间的间距iPad的用户界面,标签栏项目定位与默认的宽度和密切彼此相邻项间间距(可定制itemWidth itemSpacing属性),可能留下空间标签栏的左和右边缘
    UITabBarItemPositioningAutomatic,
//默认的标签栏项目定位在iPhone上。指定标签栏项目应该分布填补标签栏的宽度。默认的标签栏项目定位在iPhone上。指定标签栏项目应该分布填补标签栏的宽度。
    UITabBarItemPositioningFill,
//默认的标签栏项目定位在iPad上。指定标签栏项目应该定位与默认的宽度和密切彼此相邻项间间距(可定制的itemWidth和itemSpacing属性)。标签栏的项目集中在标签栏,可能留下空间标签栏的左和右边缘。默认的标签栏项目定位在iPad上。指定标签栏项目应该定位与默认的宽度和密切彼此相邻项间间距(可定制的itemWidth和itemSpacing属性)。标签栏的项目集中在标签栏,可能留下空间标签栏的左和右边缘。
    UITabBarItemPositioningCentered,
} NS_ENUM_AVAILABLE_IOS(7_0);
@class UITabBarItem;
@class UIImageView;
@protocol UITabBarDelegate;
NS_CLASS_AVAILABLE_IOS(2_0) @interface UITabBar : UIView
//弱引用。默认为零(意味着默认是不执行代理方法的)(0)
@property(nullable,nonatomic,assign) id<UITabBarDelegate> delegate;     // weak reference. default is nil
//获取/设置uitabbaritem可见。默认是零(0)
@property(nullable,nonatomic,copy) NSArray<UITabBarItem *> *items;        // get/set visible UITabBarItems. default is nil. changes not animated. shown in order
//基于模式将显示反馈。(点击之后)
@property(nullable,nonatomic,assign) UITabBarItem *selectedItem; // will show feedback based on mode. default is nil

 //将淡入或淡出或者重新排序和调整间距(动画效果)
- (void)setItems:(nullable NSArray<UITabBarItem *> *)items animated:(BOOL)animated;   // will fade in or out or reorder and adjust spacing
// Reorder items. This will display a sheet with all the items listed, allow the user to change/reorder items and shows a 'Done' button at the top
- (void)beginCustomizingItems:(NSArray<UITabBarItem *> *)items __TVOS_PROHIBITED;   // list all items that can be reordered. always animates a sheet up. visible items not listed are fixed in place
- (BOOL)endCustomizingAnimated:(BOOL)animated __TVOS_PROHIBITED;    // hide customization sheet. normally you should let the user do it. check list of items to see new layout. returns YES if layout changed
- (BOOL)isCustomizing __TVOS_PROHIBITED;
 /*
 The behavior of tintColor for bars has changed on iOS 7.0. It no longer affects the bar's background
 and behaves as described for the tintColor property added to UIView.
 To tint the bar's background, please use -barTintColor.
 */
@property(null_resettable, nonatomic,strong) UIColor *tintColor NS_AVAILABLE_IOS(5_0);
@property(nullable, nonatomic,strong) UIColor *barTintColor NS_AVAILABLE_IOS(7_0) UI_APPEARANCE_SELECTOR;  // default is nil
/* selectedImageTintColor will be applied to the gradient image used when creating the
 selected image. Default is nil and will result in the system bright blue for selected
 tab item images. If you wish to also customize the unselected image appearance, you must
 use the image and selectedImage properties on UITabBarItem along with UIImageRenderingModeAlways
 Deprecated in iOS 8.0. On iOS 7.0 and later the selected image takes its color from the
 inherited tintColor of the UITabBar, which may be set separately if necessary.
 */
@property(nullable,nonatomic,strong) UIColor *selectedImageTintColor NS_DEPRECATED_IOS(5_0,8_0,"Use tintColor") UI_APPEARANCE_SELECTOR __TVOS_PROHIBITED;
/* The background image will be tiled to fit, even if it was not created via the UIImage resizableImage methods.
 */
@property(nullable, nonatomic,strong) UIImage *backgroundImage NS_AVAILABLE_IOS(5_0) UI_APPEARANCE_SELECTOR;
/* The selection indicator image is drawn on top of the tab bar, behind the bar item icon.
 */
@property(nullable, nonatomic,strong) UIImage *selectionIndicatorImage NS_AVAILABLE_IOS(5_0) UI_APPEARANCE_SELECTOR; 
/* Default is nil. When non-nil, a custom shadow image to show instead of the default shadow image. For a custom shadow to be shown, a custom background image must also be set with -setBackgroundImage: (if the default background image is used, the default shadow image will be used).
 */
@property(nullable, nonatomic,strong) UIImage *shadowImage NS_AVAILABLE_IOS(6_0) UI_APPEARANCE_SELECTOR;
/*
 Default is UITabBarItemPositioningAutomatic. The tab bar items fill horizontally
 for the iPhone user interface idiom, and are centered with a default width and 
 inter-item spacing (customizable with the itemWidth and itemSpacing
 properties) for the iPad idiom. When the tab bar is owned by a UITabBarController
 further heuristics may determine the positioning for UITabBarItemPositioningAutomatic.
    Use UITabBarItemPositioningFill to force the items to fill horizontally.
    Use UITabBarItemPositioningCenter to force the items to center with a default
 width (or the itemWidth, if set).
 */
@property(nonatomic) UITabBarItemPositioning itemPositioning NS_AVAILABLE_IOS(7_0) UI_APPEARANCE_SELECTOR __TVOS_PROHIBITED;

/*
 Set the itemWidth to a positive value to be used as the width for tab bar items
 when they are positioned as a centered group (as opposed to filling the tab bar).
 Default of 0 or values less than 0 will be interpreted as a system-defined width.
 */
@property(nonatomic) CGFloat itemWidth NS_AVAILABLE_IOS(7_0) UI_APPEARANCE_SELECTOR;
/*
 Set the itemSpacing to a positive value to be used between tab bar items
 when they are positioned as a centered group.
 Default of 0 or values less than 0 will be interpreted as a system-defined spacing.
 */
@property(nonatomic) CGFloat itemSpacing NS_AVAILABLE_IOS(7_0) UI_APPEARANCE_SELECTOR;
/*
 Valid bar styles are UIBarStyleDefault (default) and UIBarStyleBlack.
 */
@property(nonatomic) UIBarStyle barStyle NS_AVAILABLE_IOS(7_0) UI_APPEARANCE_SELECTOR __TVOS_PROHIBITED;
/*
 Default is YES.
 You may force an opaque background by setting the property to NO.
 If the tab bar has a custom background image, the default is inferred from the alpha
 values of the image—YES if it has any pixel with alpha < 1.0
 If you send setTranslucent:YES to a tab bar with an opaque custom background imag
 the tab bar will apply a system opacity less than 1.0 to the image.
 If you send setTranslucent:NO to a tab bar with a translucent custom background image
 the tab bar will provide an opaque background for the image using the bar's barTintColor if defined, or black
 for UIBarStyleBlack or white for UIBarStyleDefault if barTintColor is nil.
 */
@property(nonatomic,getter=isTranslucent) BOOL translucent NS_AVAILABLE_IOS(7_0);
@end
//___________________________________________________________________________________________________
@protocol UITabBarDelegate<NSObject>
@optional
- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item; // called when a new view is selected by the user (but not programatically)
/* called when user shows or dismisses customize sheet. you can use the 'willEnd' to set up what appears underneath. 
 changed is YES if there was some change to which items are visible or which order they appear. If selectedItem is no longer visible, 
 it will be set to nil.
 */
- (void)tabBar:(UITabBar *)tabBar willBeginCustomizingItems:(NSArray<UITabBarItem *> *)items __TVOS_PROHIBITED;                     // called before customize sheet is shown. items is current item list
- (void)tabBar:(UITabBar *)tabBar didBeginCustomizingItems:(NSArray<UITabBarItem *> *)items __TVOS_PROHIBITED;                      // called after customize sheet is shown. items is current item list
- (void)tabBar:(UITabBar *)tabBar willEndCustomizingItems:(NSArray<UITabBarItem *> *)items changed:(BOOL)changed __TVOS_PROHIBITED; // called before customize sheet is hidden. items is new item list
- (void)tabBar:(UITabBar *)tabBar didEndCustomizingItems:(NSArray<UITabBarItem *> *)items changed:(BOOL)changed __TVOS_PROHIBITED;  // called after customize sheet is hidden. items is new item list
@end
NS_ASSUME_NONNULL_END

UItabBarItem

#import <Foundation/Foundation.h>
#import <UIKit/UIBarItem.h>
#import <UIKit/UIGeometry.h>
#import <UIKit/UIKitDefines.h>

NS_ASSUME_NONNULL_BEGIN

typedef NS_ENUM(NSInteger, UITabBarSystemItem) {
    UITabBarSystemItemMore,
    UITabBarSystemItemFavorites,
    UITabBarSystemItemFeatured,
    UITabBarSystemItemTopRated,
    UITabBarSystemItemRecents,
    UITabBarSystemItemContacts,
    UITabBarSystemItemHistory,
    UITabBarSystemItemBookmarks,
    UITabBarSystemItemSearch,
    UITabBarSystemItemDownloads,
    UITabBarSystemItemMostRecent,
    UITabBarSystemItemMostViewed,
};

@class UIView, UIImage;

NS_CLASS_AVAILABLE_IOS(2_0) @interface UITabBarItem : UIBarItem 

- (instancetype)init NS_DESIGNATED_INITIALIZER;
- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder NS_DESIGNATED_INITIALIZER;
/* The unselected image is autogenerated from the image argument. The selected image
 is autogenerated from the selectedImage if provided and the image argument otherwise.
 To prevent system coloring, provide images with UIImageRenderingModeAlwaysOriginal (see UIImage.h)
 */
//直接定义工具条标题,标题图片,及tag值
- (instancetype)initWithTitle:(nullable NSString *)title image:(nullable UIImage *)image tag:(NSInteger)tag;
//定义工具条标题,标题图片,选中之后的标题图片
- (instancetype)initWithTitle:(nullable NSString *)title image:(nullable UIImage *)image selectedImage:(nullable UIImage *)selectedImage NS_AVAILABLE_IOS(7_0);
- (instancetype)initWithTabBarSystemItem:(UITabBarSystemItem)systemItem tag:(NSInteger)tag;
//选中之后的拖欠
@property(nullable, nonatomic,strong) UIImage *selectedImage NS_AVAILABLE_IOS(7_0);
//这些方法现在已经弃用
@property(nullable, nonatomic, copy) NSString *badgeValue;    // default is nil

/*  These methods are now deprecated. Please use -initWithTitle:image:selectedImage:.
 */
- (void)setFinishedSelectedImage:(nullable UIImage *)selectedImage withFinishedUnselectedImage:(nullable UIImage *)unselectedImage NS_DEPRECATED_IOS(5_0,7_0,"Use initWithTitle:image:selectedImage: or the image and selectedImage properties along with UIImageRenderingModeAlwaysOriginal") __TVOS_PROHIBITED;
- (nullable UIImage *)finishedSelectedImage NS_DEPRECATED_IOS(5_0,7_0) __TVOS_PROHIBITED;
- (nullable UIImage *)finishedUnselectedImage NS_DEPRECATED_IOS(5_0,7_0) __TVOS_PROHIBITED;

/* To set item label text attributes use the appearance selectors available on the superclass, UIBarItem.

   Use the following to tweak the relative position of the label within the tab button (for handling visual centering corrections if needed because of custom text attributes)
 */
@property (nonatomic, readwrite, assign) UIOffset titlePositionAdjustment NS_AVAILABLE_IOS(5_0) UI_APPEARANCE_SELECTOR;

@end

NS_ASSUME_NONNULL_END

UIBarItem

#import <Foundation/Foundation.h>
#import <UIKit/UIGeometry.h>
#import <UIKit/UIKitDefines.h>
#import <UIKit/UIAppearance.h>
#import <UIKit/UIControl.h>

NS_ASSUME_NONNULL_BEGIN

@class UIImage;

NS_CLASS_AVAILABLE_IOS(2_0) @interface UIBarItem : NSObject <NSCoding, UIAppearance>

- (instancetype)init NS_DESIGNATED_INITIALIZER;
- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder NS_DESIGNATED_INITIALIZER;

@property(nonatomic,getter=isEnabled) BOOL         enabled;      // default is YES(是否可点)
@property(nullable, nonatomic,copy)             NSString    *title;        // default is nil(工具条主题名字)
@property(nullable, nonatomic,strong)           UIImage     *image;        // default is nil(工具条主题图标)
@property(nullable, nonatomic,strong)           UIImage     *landscapeImagePhone NS_AVAILABLE_IOS(5_0) __TVOS_PROHIBITED; // default is nil
@property(nonatomic)                  UIEdgeInsets imageInsets;  // default is UIEdgeInsetsZero
@property(nonatomic)                  UIEdgeInsets landscapeImagePhoneInsets NS_AVAILABLE_IOS(5_0) __TVOS_PROHIBITED;  // default is UIEdgeInsetsZero. These insets apply only when the landscapeImagePhone property is set.
@property(nonatomic)                  NSInteger    tag;          // default is 0

/* You may specify the font, text color, and shadow properties for the title in the text attributes dictionary, using the keys found in NSAttributedString.h.
 */
- (void)setTitleTextAttributes:(nullable NSDictionary<NSString *,id> *)attributes forState:(UIControlState)state NS_AVAILABLE_IOS(5_0) UI_APPEARANCE_SELECTOR;
- (nullable NSDictionary<NSString *,id> *)titleTextAttributesForState:(UIControlState)state NS_AVAILABLE_IOS(5_0) UI_APPEARANCE_SELECTOR;

@end

NS_ASSUME_NONNULL_END

定义tabBarController控制器:(UITabBarButton在UITabBar中得位置是均分的,UITabBar的高度为49。)

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tabBar.backgroundColor = [UIColor grayColor];
    
    //床架控制器
    self.V1 = [[ViewController alloc] init];
    //将控制器放入导航控制器中
    UINavigationController *navc= [[UINavigationController alloc] initWithRootViewController:self.V1];
    //设置tabBarItem的标题
    navc.tabBarItem.title = @"成长";
    //设置tabBarItem的标题图片
    navc.tabBarItem.image = [UIImage imageNamed:[NSString stringWithFormat:@"tab_growth"]];
    
//    navc.tabBarItem.image =  [self YZImageWithColor:[UIColor whiteColor] andSize:CGSizeMake(CGRectGetWidth(self.tabBar.bounds)/4, CGRectGetHeight(self.tabBar.bounds))];
    
    //设置tabBarItem标题点击之前的颜色
    [navc.tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor whiteColor],NSFontAttributeName:[UIFont boldSystemFontOfSize:10]} forState:UIControlStateNormal];
    //设置tabBarItem标题点击之后的颜色
    [navc.tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor redColor],NSFontAttributeName:[UIFont boldSystemFontOfSize:10]} forState:UIControlStateSelected];
    
    self.V3 = [[TwoViewController alloc] init];
    UINavigationController *navc1= [[UINavigationController alloc] initWithRootViewController:self.V3];
    navc1.navigationBar.barTintColor = [UIColor blueColor];
    navc1.tabBarItem.title = @"我";
    navc1.tabBarItem.image = [UIImage imageNamed:[NSString stringWithFormat:@"tab_mine"]];
    
//    navc1.tabBarItem.image =  [self YZImageWithColor:[UIColor whiteColor] andSize:CGSizeMake(CGRectGetWidth(self.tabBar.bounds)/4, CGRectGetHeight(self.tabBar.bounds))];
    
    [navc1.tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor whiteColor],NSFontAttributeName:[UIFont boldSystemFontOfSize:10]} forState:UIControlStateNormal];
    [navc1.tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor redColor],NSFontAttributeName:[UIFont boldSystemFontOfSize:10]} forState:UIControlStateSelected];
    //将控制器放入数组中
    NSArray * array = [NSArray arrayWithObjects:navc, navc1, nil];
    //将控制器
    [self setViewControllers:array animated:YES];
    //调用函数设置tabBar背景颜色
    self.tabBar.barTintColor = [UIColor purpleColor];
    //调用函数设置tabBar对应的每一个控制器点击之后的图标
    self.tabBar.selectionIndicatorImage = [self YZImageWithColor:[UIColor orangeColor] andSize:CGSizeMake(CGRectGetWidth(self.tabBar.bounds)/4, CGRectGetHeight(self.tabBar.bounds))];
    //重写UITabBarController代理
    self.delegate = self;
}

//设置图片的颜色和大小

- (UIImage *)YZImageWithColor:(UIColor *)color andSize:(CGSize)size{

CGRect rect = CGRectMake(0.0f, 0.0f, size.width, size.height);

UIGraphicsBeginImageContext(rect.size);

CGContextRef context = UIGraphicsGetCurrentContext();

CGContextSetFillColorWithColor(context, [color CGColor]);

CGContextFillRect(context, rect);

UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

return image;

}

上方代码我们能够得到想要的任何形式的固定的tabBarController但是呢我们有时候需求需要给同一个tabBar控制器的主题添加不同的功能,这时候使用普通的tabBarController已经不能够满足我们的需求了。这时候我们就用到了他的代理方法

//点击tabBarController之后调用的时间
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{

    UITabBarItem *tabBarItem = [[self.viewControllers objectAtIndex:0] tabBarItem];
    if(tabBarController.selectedIndex == 0){
        if ([tabBarItem.title isEqualToString:@"相机"]) {
            //调用相机相册
            [self yzxShowCamera];
        }
        tabBarItem.image = [UIImage imageNamed:[NSString stringWithFormat:@"tab_ camera"]];
        tabBarItem.title = @"相机";
        
    }else{
        tabBarItem.title = @"成长";
        tabBarItem.image = [UIImage imageNamed:[NSString stringWithFormat:@"tab_growth"]];
    }
}

得到能够改变的tabBar

我们使用以上方法是的我们能够定义我们想要的tabBarController了,当然我们亦可以自定义tabBarController但是这个往往会使得我们的界面更加复杂话。而且调用原声的往往更加简单.

下方的工具条称为UITabBar ,如果UITabBarController有N个子控制器,那么UITabBar内部就会有N 个UITabBarButton作为子控件与之对应。

下面的tabBar按钮显示是有tabBarItem决定的:

为TA充电
共{{data.count}}人
人已赞赏
iOS文章

iOS开发collectionView自动布局实现瀑布流

2021-6-3 13:54:24

iOS文章

iOS开发tableView扩展用法

2021-6-3 14:29:04

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索