开发iOS 技术文集干货

项目开发中封装一个BarButtonItem类别-很实用

2015-09-06  本文已影响3450人  Tuberose

Encapsulates a TabBarItem--封装一个BarButtonItem类

第一种方式:
UIImage *image = [UIImage imageNamed:@"tupian"];
UIImage *image =[button backgroundImageForState:UIControlStateNormal];
button.frame = CGRectMake(0, 0, image.size.width, image.size.height);

第二种方式:
UIImage *image = [UIImage imageNamed:@"tupian"];
UIImage *image = button.currentbackgrundImage;
button.frame = CGRectMake(0, 0, image.size.width, image.size.height);

第三种方式:
UIImage *image = [UIImage imageNamed:@"tupian"];
UIImage *image =[button backgroundImageForState:UIControlStateNormal];
[button sizeToFit];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setBackgroundImage:[UIImage imageNamed:@"MainTagSubIcon"] forState:UIControlStateNormal];
[button setBackgroundImage:[UIImage imageNamed:@"MainTagSubIconClick"] forState:UIControlStateHighlighted];
[button sizeToFit];
[button addTarget:self action:@selector(CYEssenceClick) forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];

- (void)CYEssenceClick
{
    NSLog(@"%s",__func__);
}
        UIButton *moonButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [moonButton setBackgroundImage:[UIImage imageNamed:@"mine-moon-icon"] forState:UIControlStateNormal];
        [moonButton setBackgroundImage:[UIImage imageNamed:@"mine-moon-icon-click"] forState:UIControlStateHighlighted];
        [moonButton sizeToFit];
        [moonButton addTarget:self action:@selector(moonClick) forControlEvents:UIControlEventTouchUpInside];

        UIButton *settingButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [settingButton setBackgroundImage:[UIImage imageNamed:@"mine-setting-icon"] forState:UIControlStateNormal];
        [settingButton setBackgroundImage:[UIImage imageNamed:@"mine-setting-icon-click"] forState:UIControlStateHighlighted];
        [settingButton sizeToFit];
        [settingButton addTarget:self action:@selector(settingClick) forControlEvents:UIControlEventTouchUpInside];

            self.navigationItem.rightBarButtonItems = @[
                                                   [[UIBarButtonItem alloc] initWithCustomView:settingButton],
                                                   [[UIBarButtonItem alloc] initWithCustomView:moonButton]
];

- (void)moonClick
{
    NSLog(@"%s",__func__);
}
- (void)settingClick
{
    NSLog(@"%s",__func__);
}


第一种方式

#import <UIKit/UIKit.h>

@interface CYItemTool : NSObject
+ (UIBarButtonItem *)itemWithImage:(NSString *)image highImage:(NSString *)highImage target:(id)target action:(SEL)action;
@end
#import "CYItemTool.h"

@implementation CYItemTool
+ (UIBarButtonItem *)itemWithImage:(NSString *)image highImage:(NSString *)highImage target:(id)target action:(SEL)action
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setBackgroundImage:[UIImage imageNamed:image] forState:UIControlStateNormal];
    [button setBackgroundImage:[UIImage imageNamed:highImage] forState:UIControlStateHighlighted];
    [button sizeToFit];
    [button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];

    return [[UIBarButtonItem alloc] initWithCustomView:button];
}
@end
#ifndef ___________0901_PrefixHeader_pch
#define ___________0901_PrefixHeader_pch
#import <UIKit/UIKit.h>
#import "CYItemTool.h"

// Include any system framework and library headers here that should be included in all compilation units.
// You will also need to set the Prefix Header build setting of one or more of your targets to reference this file.
// 日志输出
#ifdef DEBUG // 开发阶段 -DEBUG阶段:使用Log
#define CYLog(...) NSLog(__VA_ARGS__)
#else // 发布阶段——上线阶段:移除Log
#define CYLog(...)
#endif

// 方法输出
#define CYLogFunc CYLog(@"%s",__func__)

#endif

第二种方式

新建一个扩展类(更推荐这种)


#import <UIKit/UIKit.h>

@interface UIBarButtonItem (CYExtension)
+ (instancetype)itemWithImage:(NSString *)image highImage:(NSString *)highImage target:(id)target action:(SEL)action;
@end
#import "UIBarButtonItem+CYExtension.h"

@implementation UIBarButtonItem (CYExtension)
+ (instancetype)itemWithImage:(NSString *)image highImage:(NSString *)highImage target:(id)target action:(SEL)action
{
    {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setBackgroundImage:[UIImage imageNamed:image] forState:UIControlStateNormal];
        [button setBackgroundImage:[UIImage imageNamed:highImage] forState:UIControlStateHighlighted];
        [button sizeToFit];
        [button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];

        return [[self alloc] initWithCustomView:button];
    }
}

@end
#ifndef ___________0901_PrefixHeader_pch
#define ___________0901_PrefixHeader_pch
#import <UIKit/UIKit.h>
#import "UIBarButtonItem+CYExtension.h"

// Include any system framework and library headers here that should be included in all compilation units.
// You will also need to set the Prefix Header build setting of one or more of your targets to reference this file.
// 日志输出
#ifdef DEBUG // 开发阶段 -DEBUG阶段:使用Log
#define CYLog(...) NSLog(__VA_ARGS__)
#else // 发布阶段——上线阶段:移除Log
#define CYLog(...)
#endif

// 方法输出
#define CYLogFunc CYLog(@"%s",__func__)

#endif


#import "CYMeViewController.h"
#import "CYSettingViewController.h"

@interface CYMeViewController ()

@end

@implementation CYMeViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationItem.title = @"我的";

    // 我的导航栏右边的内容
    UIBarButtonItem *moonButton = [UIBarButtonItem itemWithImage:@"mine-moon-icon" highImage:@"mine-moon-icon-click" target:self action:@selector(moonClick)];
    UIBarButtonItem *settingButton = [UIBarButtonItem itemWithImage:@"mine-setting-icon" highImage:@"mine-setting-icon-click" target:self action:@selector(settingClick)];

    self.navigationItem.rightBarButtonItems = @[settingButton,moonButton];
}
- (void)moonClick
{
    CYLogFunc
}


- (void)settingClick
{
    CYSettingViewController *setting = [[CYSettingViewController alloc] init];
    [self.navigationController pushViewController:setting animated:YES];
}

@end
#import "CYFocusViewController.h"

@interface CYFocusViewController ()

@end

@implementation CYFocusViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationItem.title = @"我的关注";

    // 设置导航栏左边的内容
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithImage:@"friendsRecommentIcon" highImage:@"friendsRecommentIcon-click" target:self action:@selector(CYFocusViewClick)];
}
- (void)CYFocusViewClick
{
    CYLogFunc
    UITableViewController *focus = [[UITableViewController alloc] init];
    focus.navigationItem.title = @"百科不是全书";
    [self.navigationController pushViewController:focus animated:YES];

}

扩充说明--类别

创建类别

@interface NSString(NumberConvenience)-(NSNumber *)lengthAsNumber;@end//NumberConvenience
@implementation NSString(NumberConvenience)-(NSNumber *)lengthAsNumber{unsigned int length = [self length];return ([NSNumber numberWithUnsignedInt : length]);} **//lengthAsNumber**@end **//NumberConvenience

另外一篇

类别

#import <Foundation/Foundation.h>
 
@interface UIImage (UIImageExt)
//这个方法就是我添加的图片压缩的方法
- (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize;
@end
 
#import "UIImageExt.h"
 
@implementation UIImage (UIImageExt)
 
- (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize
{
UIImage *sourceImage = self;
UIImage *newImage = nil;
CGSize imageSize = sourceImage.size;
CGFloat width = imageSize.width;
CGFloat height = imageSize.height;
CGFloat targetWidth = targetSize.width;
CGFloat targetHeight = targetSize.height;
CGFloat scaleFactor = 0.0;
CGFloat scaledWidth = targetWidth;
CGFloat scaledHeight = targetHeight;
CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
 
if (CGSizeEqualToSize(imageSize, targetSize) == NO)
{
CGFloat widthFactor = targetWidth / width;
CGFloat heightFactor = targetHeight / height;
 
if (widthFactor > heightFactor)
scaleFactor = widthFactor; // scale to fit height
else
scaleFactor = heightFactor; // scale to fit width
scaledWidth= width * scaleFactor;
scaledHeight = height * scaleFactor;
 
// center the image
if (widthFactor > heightFactor)
{
thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
}
else if (widthFactor < heightFactor)
{
thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
}
}
 
UIGraphicsBeginImageContext(targetSize); // this will crop
 
CGRect thumbnailRect = CGRectZero;
thumbnailRect.origin = thumbnailPoint;
thumbnailRect.size.width= scaledWidth;
thumbnailRect.size.height = scaledHeight;
 
[sourceImage drawInRect:thumbnailRect];
 
newImage = UIGraphicsGetImageFromCurrentImageContext();
if(newImage == nil)
NSLog(@"could not scale image");
 
//pop the context to get back to the default
UIGraphicsEndImageContext();
return newImage;
}
 
@end
//根据图片tag显示图片
-(void)showPhotoBySerialNumber:(int)imageTag;
{
//这个largeImageArray是NSMutableArray类型的,存放图片存储路径,根据路径得到UIImage
UIImage *img = [UIImage imageWithContentsOfFile:[self.largeImageArray objectAtIndex:imageTag]];
//MyScrollView是我自定义的ScrollView,目的是使ScrollView响应点击事件,关于如何自定义的ScrollView在以后的博客中,我将会阐述
MyScrollView *scrView = [[MyScrollView alloc] initWithFrame:CGRectMake(340*imageTag, 0, 320, 480)];
scrView.host = self;
//这句就是调用了类别,通过UIImage实例对象,调用imageByScalingAndCroppingForSize:类别
scrView.image = [img imageByScalingAndCroppingForSize:CGSizeMake(320.0, 480.0)];
scrView.tag = imageTag+100;
//下面这句,就是把上面的scrView塞到imageScrollView上,imageScrollView是UIScrollView类型
[self.imageScrollView addSubview:scrView];
[scrView release];
 
}

二、协议

@protocol ProtocolName   //协议名
   methodDeclaration;        //方法名  @end
 @interface ClassName : ParentClassName < ProtocolName>

实例分析

#import <Foundation/Foundation.h>
//协议ImageTouchDelegate
@protocol ImageTouchDelegate
//协议中声明的方法
-(void)imageTouch:(NSSet *)touches withEvent:(UIEvent *)event whichView:(id)imageView;
@end
 
@interface ImageTouchView : UIImageView {
id<ImageTouchDelegate>  delegate;
}
@property(nonatomic,assign)id<ImageTouchDelegate> delegate;
@end
#import "ImageTouchView.h"
 
 
@implementation ImageTouchView
@synthesize delegate;
 
-(id)initWithFrame:(CGRect)frame
{
if (self == [super initWithFrame:frame])
{
[self setUserInteractionEnabled:YES];
}
return  self;
}
-(BOOL)touchesShouldBegin:(NSSet *)touches withEvent:(UIEvent *)event inContentView:(UIView *)view
{
return YES;
}
 
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[delegate imageTouch:touches withEvent:event whichView:self];
}
 
@end
#import <UIKit/UIKit.h>
//引入定义协议ImageTouchDelegate的头文件
#import "ImageTouchView.h"
//把协议名放到父头后面的尖括号里面,如果有多个协议,用逗号分隔
@interface PhotoOnShotViewController : UIViewController<ImageTouchDelegate> {
 
}
 
@end
#import "PhotoOnShotViewController.h"
 
@implementation PhotoOnShotViewController
 
 
 
//实现协议中定义的方法,
-(void)imageTouch:(NSSet *)touches withEvent:(UIEvent *)event whichView:(id)imageView{
 
}
上一篇 下一篇

猜你喜欢

热点阅读