1、外部定义类来实现方法:
在定义方法的时候需要继承 ViewController
不如说类名为 addButton
在.h文件声明
-(UIButton *)addImagebutton:(NSString *)imageName withCGRect:(CGRect)frame;
为什么合理要有返回值呢?在后面添加方法的时候,有一个button接受一个值,就是这里的 返回值 UIButton
添加方法之后, 这个方法是实现直接添加一个按钮图片 在 .m 文件里面实现
-(UIButton *)addImagebutton:(NSString *)imageName withCGRect:(CGRect)frame{
UIButton *but = [UIButton buttonWithType:UIButtonTypeCustom];
but.frame = frame;
[but setTitle:imageName forState:UIControlStateNormal];
[but setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
return but;
}
方法就这样定义完了
然后在其他的类里面调用这个方法:
首先对导入头文件
#import "AddbuttonandimageViewController.h"
导入之后定义一个类对象
AddbuttonandimageViewController *button;
并且初始化对象
button = [[AddbuttonandimageViewController alloc] init];
UIButton *button1 = [button addImagebutton:@"按钮" withCGRect:CGRectMake(100, 100, 100, 50)];
[self.view addSubview:button1];
UIButton *button2 = [button addImagebutton:@"按钮" withCGRect:CGRectMake(100, 300, 100, 50)];
[self.view addSubview:button2];
在定义方法的时候是不能直接把 self.view addSuview: btn 写进去的,因为直接加进去的话,这个对象是加在了自定义对象的所对应的xib文件里面
这种方法就可以实现减少代码量,而且方便查看代码
2、类内部实现方法:
这个就比较简单
在头文件 .h 里面声明方法名
-(UIImageView *)AddImageView:(NSString *)imageName withCGRect:(CGRect)frame;
然后在类里面实现方法
-(UIImageView *)AddImageView:(NSString *)imageName withCGRect:(CGRect)frame{
UIImageView *imageView = [[UIImageView alloc] initWithFrame:frame];
[imageView setImage:[UIImage imageNamed:imageName]];
[imageName release];
[self.view addSubview:imageView];
return imageView;
}
实现了之后,就可以直接调用
[self AddImageView:@"按钮" withCGRect:CGRectMake(150, 100, 100, 100)];
这样就完成了