美文网首页iOS开发知识小集
iOS 封装重写导航按钮方法

iOS 封装重写导航按钮方法

作者: 达_Ambition | 来源:发表于2018-07-17 09:41 被阅读22次
    封装的.h文件
    //  UIBarItem+YD.h
    //  powerMall
    //
    //  Created by mac on 2018/7/16.
    //  Copyright © 2018年 taisheng. All rights reserved.
    //
    
    #import <UIKit/UIKit.h>
    
    @interface UIBarItem (YD)
    //封装导航图片按钮
    +(UIBarButtonItem *)itemWithImageName:(NSString *)imageName HighImageName:(NSString *)highImageName target:(id)target action:(SEL)action type:(int)type;
    //封装导航文字按钮
    +(UIBarButtonItem *)itemWithTitleName:(NSString *)titleName HighTitleName:(NSString *)highTitleName target:(id)target action:(SEL)action;
    @end
    
    封装的.m文件
    //  UIBarItem+YD.m
    //  powerMall
    //
    //  Created by mac on 2018/7/16.
    //  Copyright © 2018年 taisheng. All rights reserved.
    //
    
    #import "UIBarItem+YD.h"
    #define AdaptedWidth(x)  ceilf((x) * kScreenWidthRatio)
    @implementation UIBarItem (YD)
    +(UIBarButtonItem *)itemWithImageName:(NSString *)imageName HighImageName:(NSString *)highImageName target:(id)target action:(SEL)action type:(int)type{
        UIButton *button=[UIButton buttonWithType:UIButtonTypeCustom];
        [button setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
        //type=1右导航按钮,否则为左导航按钮
        if (type ==1) {
            button.frame =CGRectMake(15, 5, 30, 30);
        }else{
            button.frame =CGRectMake(0, 10, 20, 20);
        }
        
        button.imageView.contentMode=UIViewContentModeScaleAspectFit;
        [button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
        button.adjustsImageWhenHighlighted=NO;
        //修改方法
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
        [view addSubview:button];
        return [[UIBarButtonItem alloc]initWithCustomView:view];
        
    }
    +(UIBarButtonItem *)itemWithTitleName:(NSString *)titleName HighTitleName:(NSString *)highTitleName target:(id)target action:(SEL)action{
        //导航栏按钮
        UIButton * Button=[UIButton buttonWithType:UIButtonTypeCustom];
        Button.titleLabel.font=[UIFont systemFontOfSize:17];
        Button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
        [Button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [Button setTitle:titleName forState:UIControlStateNormal];
        [Button setTitle:highTitleName forState:UIControlStateHighlighted];
        //按钮的大小为当前按钮的大小
        Button.frame = CGRectMake(0, 0, 44, 44);
        [Button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
        return [[UIBarButtonItem alloc]initWithCustomView:Button];
    }
    @end
    
    

    相关文章

      网友评论

        本文标题:iOS 封装重写导航按钮方法

        本文链接:https://www.haomeiwen.com/subject/cncwpftx.html