iOS 封装重写导航按钮方法

封装的.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

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • mean to add the formatted="false" attribute?.[ 46% 47325/...
    ProZoom阅读 2,726评论 0 3
  • 1、通过CocoaPods安装项目名称项目信息 AFNetworking网络请求组件 FMDB本地数据库组件 SD...
    阳明AGI阅读 16,018评论 3 119
  • ## 可重入函数 ### 可重入性的理解 若一个程序或子程序可以安全的被并行执行,则称其为可重入的;即当该子程序正...
    夏至亦韵阅读 730评论 0 0
  • 姓名:蒋荣信 公司:惠州市以泰克电线电缆有限公司 组别:第230期努力二组 【日精进打卡第 4天】 【知~学习】 ...
    蒋荣信阅读 339评论 0 0
  • 快乐工作,快乐生活。一个有凝聚力德团队需要是一个快乐的团队,这次员工户外活动定在大夫山森林公园,恰逢九月九一个团聚...
    妍旺旺阅读 119评论 0 0