-
Notifications
You must be signed in to change notification settings - Fork 2
/
UIViewController+LeftBarItem.m
94 lines (79 loc) · 2.87 KB
/
UIViewController+LeftBarItem.m
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
//
// UIViewController+LeftBarItem.m
// Test0113NavigationBackBar
//
// Created by markss on 15/1/13.
// Copyright (c) 2015年 GL. All rights reserved.
//
#import "UIViewController+LeftBarItem.h"
#import <objc/runtime.h>
static const void *LeftBarItemBlockKey = &LeftBarItemBlockKey;
@implementation UIViewController (LeftBarItem)
- (void)setLeftBarItemTitle:(NSString *)title {
[self setLeftBarItemTitle:title
image:nil
callback:nil];
}
- (void)setLeftBarItemTitle:(NSString *)title
callback:(void(^)(UIViewController *vc))callback {
[self setLeftBarItemTitle:title
image:nil
callback:callback];
}
- (void)setLeftBarItemImage:(UIImage *)image {
[self setLeftBarItemTitle:nil
image:image
callback:nil];
}
- (void)setLeftBarItemImage:(UIImage *)image
callback:(void(^)(UIViewController *vc))callback {
[self setLeftBarItemTitle:nil
image:image
callback:callback];
}
- (void)setLeftBarItemTitle:(NSString *)title
image:(UIImage *)image {
[self setLeftBarItemTitle:title
image:image
callback:nil];
}
- (void)setLeftBarItemTitle:(NSString *)title
image:(UIImage *)image
callback:(void(^)(UIViewController *vc))callback {
UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
CGSize size;
if (title) {
[button setTitle:title forState:UIControlStateNormal];
[button.titleLabel setFont:[UIFont systemFontOfSize:15.0]];
size = [button.titleLabel sizeThatFits:CGSizeMake(60, 30)];
[button setTitleEdgeInsets:UIEdgeInsetsMake(0, -10, 0, 0)];
}
if (image) {
[button setImage:image forState:UIControlStateNormal];
if (!title) {
size = image.size;
} else {
size.width += image.size.width;
size.height = size.height > image.size.height ? size.height : image.size.height;
}
[button setImageEdgeInsets:UIEdgeInsetsMake(0, -10, 0, 0)];
}
button.frame = CGRectMake(0, 0, size.width, size.height);
if (callback) {
objc_setAssociatedObject(self, LeftBarItemBlockKey, callback, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
[button addTarget:self
action:@selector(popBack:)
forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
}
#pragma private function
- (void)popBack:(id)sender {
void (^callback)(UIViewController *vc) = objc_getAssociatedObject(self, LeftBarItemBlockKey);
if (callback) {
callback(self);
} else {
[self.navigationController popViewControllerAnimated:YES];
}
}
@end