UIButton+YOHO.m
1.64 KB
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
//
// UIButton+YOHO.m
// YH_Mall
//
// Created by Haizi on 16/2/23.
// Copyright © 2016年 YOHO. All rights reserved.
//
#import "UIButton+YOHO.h"
@implementation UIButton (YOHO)
+ (instancetype)yh_buttonWithImageName:(NSString *)imageName highlightedImageName:(NSString *)highlightedImageName title:(NSString *)title target:(id)target action:(SEL)action
{
UIImage *image = [UIImage imageNamed:imageName];
UIImage *highlightedImage = nil;
if (highlightedImageName != nil) {
highlightedImage = [UIImage imageNamed:highlightedImageName];
}
CGSize imageSize = [image size];
CGSize highlightedImageSize = [highlightedImage size];
if (highlightedImageName != nil) {
if (!image || !highlightedImage) {
return nil;
}
if (!CGSizeEqualToSize(imageSize, highlightedImageSize)) {
return nil;
}
}
else {
if (!image) {
return nil;
}
}
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0.0f, 0.0f, imageSize.width, imageSize.height)];
button.exclusiveTouch = YES;
if (title != nil) {
[button setTitle:title forState:UIControlStateNormal];
[button.titleLabel setFont:[UIFont boldSystemFontOfSize:12.0f]];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
}
[button setBackgroundImage:image forState:UIControlStateNormal];
if (highlightedImageName) {
[button setBackgroundImage:highlightedImage forState:UIControlStateHighlighted];
}
[button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
return button;
}
@end