分别用label和imageView来实现button

用label和imageView实现button的功能 其中点击方法使用手势来写的

首先创建两个类 一个是用label实现button的类 另一个是用imageView来实现button的类 这两个类都是“+”方法 都继承于UIView 返回值分别是label和imageView

#import 

@interface LabelButton : UIView
+ (UILabel *)createButtonFrame:       (CGRect)frame view:(UIView *)view    buttonName:(NSString *)buttonName color:(UIColor *)color tap:  (UITapGestureRecognizer *)tap;

@end


#import "LabelButton.h"

@implementation LabelButton
+ (UILabel *)createButtonFrame:    (CGRect)frame view:(UIView *)view buttonName:(NSString *)buttonName color:(UIColor *)color tap:(UITapGestureRecognizer *)tap {
UILabel *label = [[UILabel alloc] initWithFrame:frame];
label.text = buttonName;
label.backgroundColor = color;
[view addSubview:label];
label.userInteractionEnabled = YES;
[label addGestureRecognizer:tap];

return label;
}

@end


#import 

@interface ImageViewButton : UIView
+ (UIImageView *)createButtonFrame:(CGRect)frame view:(UIView *)view image:(UIImage *)image tap:(UITapGestureRecognizer *)tap;

@end

#import "ImageViewButton.h"

@implementation ImageViewButton
+ (UIImageView *)createButtonFrame: (CGRect)frame view:(UIView *)view image:(UIImage *)image tap:(UITapGestureRecognizer *)tap {
UIImageView *imageView = [[UIImageView alloc] initWithFrame:frame];
UIImage *buttonImage = image;
[imageView setImage:buttonImage];
imageView.userInteractionEnabled = YES;
[view addSubview:imageView];
[imageView addGestureRecognizer:tap];
return imageView;
}
@end


#import "ViewController.h"
#import "LabelButton.h"
#import "ImageViewButton.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = [UIColor whiteColor];
UILabel *label = [[UILabel alloc] init];
UITapGestureRecognizer *labelTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labelClick:)];
label = [LabelButton createButtonFrame:CGRectMake(20, 100, 90, 30) view:self.view buttonName:@"确认" color:[UIColor redColor] tap:labelTap];

UIImageView *imageView = [[UIImageView alloc]init];
UITapGestureRecognizer *imageButtonTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageClick:)];
imageView = [ImageViewButton createButtonFrame:CGRectMake(20, 150, 260, 150) view:self.view image:[UIImage imageNamed:@"u=3730821670,510701542&fm=21&gp=0.jpg"] tap:imageButtonTap];

}
- (void)labelClick:(UITapGestureRecognizer *)tap {
NSLog(@"确认就确认呗");
}

- (void)imageClick:(UITapGestureRecognizer *)tap {
NSLog(@"我最可爱 哼");
}

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

@end

你可能感兴趣的:(分别用label和imageView来实现button)