我创建了一个自定义的UIView类。我想在调用backButton时调用一个动作。需要在所有视图控制器中重用此UIView类以及操作。我可以在UIView类中自己编写或查看控制器吗?
#import "CustomView.h"
@implementation CustomView
- (instancetype)init {
if(self = [super init]){
//-------------------custom headerView----------------
self.headerView = [[UIView alloc]init];
self.headerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 40);
self.headerView.backgroundColor = [UIColor redColor];
[self addSubview:self.headerView];
self.backButton = [[UIButton alloc]initWithFrame:CGRectMake(5,13, 12, 16)];
[self.backButton setImage:[UIImage imageNamed:@"back-btn.png"]
forState:UIControlStateNormal];
[self.backButton addTarget:self
action:@selector(backButtonAction)
forControlEvents:UIControlEventTouchUpInside];
[self.headerView addSubview:self.backButton];
}
return self;
}
BackButton Action
-(void)backButtonAction{
[[self navigationController] popViewControllerAnimated:YES];
}
答案 0 :(得分:4)
它很简单
您必须为UIViewController
1> UIViewController+Additions
制作类别
点击File
- > New
- > File
点击Objective-C file
中Sources
下的iOS
,然后点击下一步
现在在File Type:
下选择Category
然后设置文件名:Additions
并设置类:UIViewController
<强>的UIViewController + Additions.h 强>
首先在.h &gt;&gt;
-(void)addBackButton;
<强>的UIViewController + Additions.m 强>
-(void)addBackButton
{
self.navigationItem.leftBarButtonItem = nil;
UIButton *aBtn = [UIButton buttonWithType:UIButtonTypeCustom];
// [aBtn setTitle:@"Back" forState:UIControlStateNormal];
[aBtn setImage:[UIImage imageNamed:@"back-btn.png"] forState:UIControlStateNormal];
[aBtn setFrame:CGRectMake(0, 0,50, 64)];
[aBtn.titleLabel setFont:[UIFont systemFontOfSize:18.0]];
aBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
aBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
aBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
[aBtn setTitleColor:[UIColor colorWithRed:1/255.0 green:65/255.0 blue:96/255.0 alpha:1.0] forState:UIControlStateNormal];
[aBtn addTarget:self action:@selector(backButtonAction) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *aBarBtn = [[UIBarButtonItem alloc]initWithCustomView:aBtn];
self.navigationItem.leftBarButtonItem = aBarBtn;
}
-(void)backButtonAction
{
[self.navigationController popViewControllerAnimated:YES];
}
像这样使用:
只需在任何viewcontroller类#import "UIViewController+Additions.h"
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[self addBackButton];
}