快速创建UIBarButtonItem

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#import <UIKit/UIKit.h>

@interface UIBarButtonItem (ZDExtension)

/**
font=16,白色
*/
+ (instancetype)itemWithTitle:(NSString *)title
target:(id)target
action:(SEL)action;

/**
可自定义title的富文本
*/
+ (instancetype)itemWithTitle:(NSString *)title
attributes:(NSDictionary *)attributes
target:(id)target
action:(SEL)action;


/**
使用initWithCustomView
*/
+ (instancetype)itemWithImage:(NSString *)image
target:(id)target
action:(SEL)action;

+ (instancetype)itemWithImage:(NSString *)image
highlightedImage:(NSString *)highlightedImage
target:(id)target
action:(SEL)action;

@end
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#import "UIBarButtonItem+ZDExtension.h"

@implementation UIBarButtonItem (ZDExtension)

+ (instancetype)itemWithTitle:(NSString *)title
target:(id)target
action:(SEL)action
{
return [self itemWithTitle:title
attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:16],
NSForegroundColorAttributeName : [UIColor whiteColor]}
target:target
action:action];
}

+ (instancetype)itemWithTitle:(NSString *)title
attributes:(NSDictionary *)attributes
target:(id)target
action:(SEL)action
{
UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
[button setTitle:title forState:UIControlStateNormal];
[button setTitleColor:attributes[NSForegroundColorAttributeName] forState:UIControlStateNormal];
button.titleLabel.font = attributes[NSFontAttributeName];
[button sizeToFit];
[button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
return [[self alloc] initWithCustomView:button];
}

+ (instancetype)itemWithImage:(NSString *)image
target:(id)target
action:(SEL)action
{
return [self itemWithImage:image
highlightedImage:nil
target:target
action:action];
}

+ (instancetype)itemWithImage:(NSString *)image
highlightedImage:(NSString *)highlightedImage
target:(id)target
action:(SEL)action
{
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:[UIImage imageNamed:image] forState:UIControlStateNormal];
[button setImage:[UIImage imageNamed:highlightedImage] forState:UIControlStateHighlighted];
[button sizeToFit];
[button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
return [[self alloc] initWithCustomView:button];
}

@end

快速创建UIBarButtonItem
http://example.com/2018/05/11/快速创建UIBarButtonItem/
作者
guanzhendong
发布于
2018年5月11日
许可协议