IOS次日-新浪微博 - 添加搜索框,彈出下拉菜單 ,代理的使用 ,HWTabBar.h(自定義TabBar)

********HWDiscoverViewController.m(發現)windows

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // 建立搜索框對象
    HWSearchBar *searchBar = [HWSearchBar searchBar];
    searchBar.width = 300;
    searchBar.height = 30;
    self.navigationItem.titleView = searchBar;  //設置titleView 是搜索框
}

HWSearchBar.mdom

#import "HWSearchBar.h"

@implementation HWSearchBar

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.font = [UIFont systemFontOfSize:15];
        self.placeholder = @"請輸入搜索條件";          //hit的提示信息
        self.background = [UIImage imageNamed:@"searchbar_textfield_background"];
        
        // 經過init來建立初始化絕大部分控件,控件都是沒有尺寸
        UIImageView *searchIcon = [[UIImageView alloc] init];
        searchIcon.image = [UIImage imageNamed:@"searchbar_textfield_search_icon"];
        searchIcon.width = 30;
        searchIcon.height = 30;
        searchIcon.contentMode = UIViewContentModeCenter;  //居中
        self.leftView = searchIcon;
        self.leftViewMode = UITextFieldViewModeAlways;
    }
    return self;
}

+ (instancetype)searchBar
{
    return [[self alloc] init];
}

@end

HWSearchBar.hide

#import <UIKit/UIKit.h>

@interface HWSearchBar : UITextField
+ (instancetype)searchBar;
@end

**************HWHomeViewController.m(彈出下拉菜單)主頁面this

#import "HWHomeViewController.h"
#import "HWDropdownMenu.h"
#import "HWTitleMenuViewController.h"

@interface HWHomeViewController () <HWDropdownMenuDelegate>

@end

@implementation HWHomeViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    /* 設置導航欄上面的內容 */
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithTarget:self action:@selector(friendSearch) image:@"navigationbar_friendsearch" highImage:@"navigationbar_friendsearch_highlighted"];
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithTarget:self action:@selector(pop) image:@"navigationbar_pop" highImage:@"navigationbar_pop_highlighted"];
    
    /* 中間的標題按鈕 */
//    UIButton *titleButton = [UIButton buttonWithType:UIButtonTypeCustom];
    UIButton *titleButton = [[UIButton alloc] init];
    titleButton.width = 150;
    titleButton.height = 30;
//    titleButton.backgroundColor = HWRandomColor;
    
    // 設置圖片和文字
    [titleButton setTitle:@"首頁" forState:UIControlStateNormal];
    [titleButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    titleButton.titleLabel.font = [UIFont boldSystemFontOfSize:17];
    [titleButton setImage:[UIImage imageNamed:@"navigationbar_arrow_down"] forState:UIControlStateNormal];
    [titleButton setImage:[UIImage imageNamed:@"navigationbar_arrow_up"] forState:UIControlStateSelected];
//    titleButton.imageView.backgroundColor = [UIColor redColor];
//    titleButton.titleLabel.backgroundColor = [UIColor blueColor];
    titleButton.imageEdgeInsets = UIEdgeInsetsMake(0, 70, 0, 0); // 距離左邊
    titleButton.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 40);    // 距離右邊
    
    // 監聽標題點擊
    [titleButton addTarget:self action:@selector(titleClick:) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.titleView = titleButton;
    // 若是圖片的某個方向上不規則,好比有突起,那麼這個方向就不能拉伸
}

/**
 *  標題點擊
 */
- (void)titleClick:(UIButton *)titleButton
{
    // 1.建立下拉菜單
    HWDropdownMenu *menu = [HWDropdownMenu menu];
    menu.delegate = self;
    
    // 2.設置內容
    HWTitleMenuViewController *vc = [[HWTitleMenuViewController alloc] init];
    vc.view.height = 150;
    vc.view.width = 150;
    menu.contentController = vc;
    
    // 3.顯示
    [menu showFrom:titleButton];
}

- (void)friendSearch
{
    NSLog(@"friendSearch");
}

- (void)pop
{
    NSLog(@"pop");
}

#pragma mark - HWDropdownMenuDelegate
/**
 *  下拉菜單被銷燬了
 */
- (void)dropdownMenuDidDismiss:(HWDropdownMenu *)menu
{
    UIButton *titleButton = (UIButton *)self.navigationItem.titleView;
    titleButton.selected = NO;
    // 讓箭頭向下
//    [titleButton setImage:[UIImage imageNamed:@"navigationbar_arrow_down"] forState:UIControlStateNormal];
}

/**
 *  下拉菜單顯示了
 */
- (void)dropdownMenuDidShow:(HWDropdownMenu *)menu
{
    UIButton *titleButton = (UIButton *)self.navigationItem.titleView;
    titleButton.selected = YES;
    // 讓箭頭向上
//    [titleButton setImage:[UIImage imageNamed:@"navigationbar_arrow_up"] forState:UIControlStateNormal];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return 0;
}


@end

********************HWDropdownMenu.m(菜單的view)atom

#import "HWDropdownMenu.h"
@interface HWDropdownMenu()
/**
 *  未來用來顯示具體內容的容器
 */
@property (nonatomic, weak) UIImageView *containerView;
@end

@implementation HWDropdownMenu

- (UIImageView *)containerView
{
    if (!_containerView) {
        // 添加一個灰色圖片控件
        UIImageView *containerView = [[UIImageView alloc] init];
        containerView.image = [UIImage imageNamed:@"popover_background"];    //黑色背景圖片
        containerView.userInteractionEnabled = YES; // 開啓交互
        [self addSubview:containerView];
        self.containerView = containerView;
    }
    return _containerView;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // 清除顏色
        self.backgroundColor = [UIColor clearColor];
    }
    return self;
}


+ (instancetype)menu
{
    return [[self alloc] init];
}

- (void)setContent:(UIView *)content
{
    _content = content;
    
    // 調整內容的位置
    content.x = 10;
    content.y = 15;
    
    // 調整內容的寬度
//    content.width = self.containerView.width - 2 * content.x;
    
    // 設置灰色的高度
    self.containerView.height = CGRectGetMaxY(content.frame) + 11;
    // 設置灰色的寬度
    self.containerView.width = CGRectGetMaxX(content.frame) + 10;
    
    // 添加內容到灰色圖片中
    [self.containerView addSubview:content];
}

- (void)setContentController:(UIViewController *)contentController
{
    _contentController = contentController;
    
    self.content = contentController.view;
}

/**
 *  顯示
 */
- (void)showFrom:(UIView *)from
{
    // 1.得到最上面的窗口
    UIWindow *window = [[UIApplication sharedApplication].windows lastObject];
    
    // 2.添加本身到窗口上
    [window addSubview:self];
    
    // 3.設置尺寸
    self.frame = window.bounds;
    
    // 4.調整灰色圖片的位置
    // 默認狀況下,frame是以父控件左上角爲座標原點
    // 轉換座標系
    CGRect newFrame = [from convertRect:from.bounds toView:window];
//    CGRect newFrame = [from.superview convertRect:from.frame toView:window];
    self.containerView.centerX = CGRectGetMidX(newFrame);
    self.containerView.y = CGRectGetMaxY(newFrame);
    
    // 通知外界,本身顯示了
    if ([self.delegate respondsToSelector:@selector(dropdownMenuDidShow:)]) {
        [self.delegate dropdownMenuDidShow:self];
    }
}

/**
 *  銷燬
 */
- (void)dismiss
{
    [self removeFromSuperview];
    
    // 通知外界,本身被銷燬了
    if ([self.delegate respondsToSelector:@selector(dropdownMenuDidDismiss:)]) {
        [self.delegate dropdownMenuDidDismiss:self];
    }
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self dismiss];
}
@end

HWDropdownMenu.hspa

#import <UIKit/UIKit.h>

@class HWDropdownMenu;

@protocol HWDropdownMenuDelegate <NSObject>
@optional
- (void)dropdownMenuDidDismiss:(HWDropdownMenu *)menu;
- (void)dropdownMenuDidShow:(HWDropdownMenu *)menu;
@end

@interface HWDropdownMenu : UIView
@property (nonatomic, weak) id<HWDropdownMenuDelegate> delegate;    //代理

+ (instancetype)menu;

/**
 *  顯示
 */
- (void)showFrom:(UIView *)from;
/**
 *  銷燬
 */
- (void)dismiss;

/**
 *  內容
 */
@property (nonatomic, strong) UIView *content;
/**
 *  內容控制器
 */
@property (nonatomic, strong) UIViewController *contentController;
@end

*********HWTitleMenuViewController //彈出窗體裏面的view代理

#import "HWTitleMenuViewController.h"

@interface HWTitleMenuViewController ()

@end

@implementation HWTitleMenuViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ID = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
    }
    
    if (indexPath.row == 0) {
        cell.textLabel.text = @"好友";
    } else if (indexPath.row == 1) {
        cell.textLabel.text = @"密友";
    } else if (indexPath.row == 2) {
        cell.textLabel.text = @"所有";
    }
    
    return cell;
}
@end

**********HWTabBarViewController.mcode

#import "HWTabBarViewController.h"
#import "HWHomeViewController.h"
#import "HWMessageCenterViewController.h"
#import "HWDiscoverViewController.h"
#import "HWProfileViewController.h"
#import "HWNavigationController.h"
#import "HWTabBar.h"

@interface HWTabBarViewController () <HWTabBarDelegate>

@end

@implementation HWTabBarViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // 1.初始化子控制器
    HWHomeViewController *home = [[HWHomeViewController alloc] init];
    [self addChildVc:home title:@"首頁" image:@"tabbar_home" selectedImage:@"tabbar_home_selected"];
    
    HWMessageCenterViewController *messageCenter = [[HWMessageCenterViewController alloc] init];
    [self addChildVc:messageCenter title:@"消息" image:@"tabbar_message_center" selectedImage:@"tabbar_message_center_selected"];
    
    HWDiscoverViewController *discover = [[HWDiscoverViewController alloc] init];
    [self addChildVc:discover title:@"發現" image:@"tabbar_discover" selectedImage:@"tabbar_discover_selected"];
    
    HWProfileViewController *profile = [[HWProfileViewController alloc] init];
    [self addChildVc:profile title:@"" image:@"tabbar_profile" selectedImage:@"tabbar_profile_selected"];
    
    // 2.更換系統自帶的tabbar // self.tabBar = [[HWTabBar alloc] init];
    HWTabBar *tabBar = [[HWTabBar alloc] init]; tabBar.delegate = self; //代理 [self setValue:tabBar forKeyPath:@"tabBar"]; //    self.tabBar = tabBar;
    
//    Person *p = [[Person allooc] init];
//    p.name = @"jack";
//    [p setValue:@"jack" forKeyPath:@"name"];
}

//- (void)viewDidAppear:(BOOL)animated
//{
//    [super viewDidAppear:animated];
//    
//    int count = self.tabBar.subviews.count;
//    for (int i = 0; i<count; i++) {
//        UIView *child = self.tabBar.subviews[i];
//        Class class = NSClassFromString(@"UITabBarButton");
//        if ([child isKindOfClass:class]) {
//            child.width = self.tabBar.width / count;
//        }
//    }
//}

/**
 *  添加一個子控制器
 *
 *  @param childVc       子控制器
 *  @param title         標題
 *  @param image         圖片
 *  @param selectedImage 選中的圖片
 */
- (void)addChildVc:(UIViewController *)childVc title:(NSString *)title image:(NSString *)image selectedImage:(NSString *)selectedImage
{
    // 設置子控制器的文字
    childVc.title = title; // 同時設置tabbar和navigationBar的文字     //兩個一塊兒設置
//    childVc.tabBarItem.title = title; // 設置tabbar的文字
//    childVc.navigationItem.title = title; // 設置navigationBar的文字
    
    // 設置子控制器的圖片
    childVc.tabBarItem.image = [UIImage imageNamed:image];
    childVc.tabBarItem.selectedImage = [[UIImage imageNamed:selectedImage]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
    // 設置文字的樣式
    NSMutableDictionary *textAttrs = [NSMutableDictionary dictionary];
    textAttrs[NSForegroundColorAttributeName] = HWColor(123, 123, 123);
    NSMutableDictionary *selectTextAttrs = [NSMutableDictionary dictionary];
    selectTextAttrs[NSForegroundColorAttributeName] = [UIColor orangeColor];
    [childVc.tabBarItem setTitleTextAttributes:textAttrs forState:UIControlStateNormal];  //默認的文字顏色
    [childVc.tabBarItem setTitleTextAttributes:selectTextAttrs forState:UIControlStateSelected];
//    childVc.view.backgroundColor = HWRandomColor;
    
    // 先給外面傳進來的小控制器 包裝 一個導航控制器
    HWNavigationController *nav = [[HWNavigationController alloc] initWithRootViewController:childVc];
    // 添加爲子控制器
    [self addChildViewController:nav];
}

#pragma mark - HWTabBarDelegate代理方法
- (void)tabBarDidClickPlusButton:(HWTabBar *)tabBar { UIViewController *vc = [[UIViewController alloc] init]; vc.view.backgroundColor = [UIColor redColor]; [self presentViewController:vc animated:YES completion:nil]; } @end

****************HWTabBar.h(自定義TabBar)orm

#import "HWTabBar.h"

@interface HWTabBar()
@property (nonatomic, weak) UIButton *plusBtn;
@end

@implementation HWTabBar

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // 添加一個按鈕到tabbar中
        UIButton *plusBtn = [[UIButton alloc] init];
        [plusBtn setBackgroundImage:[UIImage imageNamed:@"tabbar_compose_button"] forState:UIControlStateNormal];
        [plusBtn setBackgroundImage:[UIImage imageNamed:@"tabbar_compose_button_highlighted"] forState:UIControlStateHighlighted];
        [plusBtn setImage:[UIImage imageNamed:@"tabbar_compose_icon_add"] forState:UIControlStateNormal];
        [plusBtn setImage:[UIImage imageNamed:@"tabbar_compose_icon_add_highlighted"] forState:UIControlStateHighlighted];
        plusBtn.size = plusBtn.currentBackgroundImage.size;
        [plusBtn addTarget:self action:@selector(plusClick) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:plusBtn];
        self.plusBtn = plusBtn;
    }
    return self;
}

/**
 *  加號按鈕點擊
 */
- (void)plusClick        //通知代理
{
    // 通知代理
    if ([self.delegate respondsToSelector:@selector(tabBarDidClickPlusButton:)]) { [self.delegate tabBarDidClickPlusButton:self]; }
}

- (void)layoutSubviews
{
#warning [super layoutSubviews] 必定要調用
    [super layoutSubviews];
    
    // 1.設置加號按鈕的位置
    self.plusBtn.centerX = self.width * 0.5;
    self.plusBtn.centerY = self.height * 0.5;
    
    // 2.設置其餘tabbarButton的位置和尺寸
    CGFloat tabbarButtonW = self.width / 5;
    CGFloat tabbarButtonIndex = 0;
    for (UIView *child in self.subviews) {
        Class class = NSClassFromString(@"UITabBarButton");
        if ([child isKindOfClass:class]) {     //若是是UITabBarButton
            // 設置寬度
            child.width = tabbarButtonW;
            // 設置x
            child.x = tabbarButtonIndex * tabbarButtonW;

            // 增長索引
            tabbarButtonIndex++;
            if (tabbarButtonIndex == 2) {
                tabbarButtonIndex++;
            }
        }
    }
    
//    int count = self.subviews.count;
//    for (int i = 0; i<count; i++) {
//        UIView *child = self.subviews[i];
//        Class class = NSClassFromString(@"UITabBarButton");
//        if ([child isKindOfClass:class]) {
//            // 設置寬度
//            child.width = tabbarButtonW;
//            // 設置x
//            child.x = tabbarButtonIndex * tabbarButtonW;
//            
//            // 增長索引
//            tabbarButtonIndex++;
//            if (tabbarButtonIndex == 2) {
//                tabbarButtonIndex++;
//            }
//        }
//    }
}

@end

****************HWTabBar.h(自定義TabBar)對象

#import <UIKit/UIKit.h>

@class HWTabBar;

#warning 由於HWTabBar繼承自UITabBar,因此稱爲HWTabBar的代理,也必須實現UITabBar的代理協議
@protocol HWTabBarDelegate <UITabBarDelegate>
@optional
- (void)tabBarDidClickPlusButton:(HWTabBar *)tabBar;
@end

@interface HWTabBar : UITabBar
@property (nonatomic, weak) id<HWTabBarDelegate> delegate;
@end
相關文章
相關標籤/搜索