我创建了一个自定义 UIView 类。每当调用 backButton 时,我都想调用一个 Action 。需要在所有 View Controller 中重用此 UIView 类以及操作。我可以在 UIView 类本身或 View Controller 中编写吗?
#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;
}
后退按钮 Action
-(void)backButtonAction{
[[self navigationController] popViewControllerAnimated:YES];
}
最佳答案
这很简单
您必须为 UIViewController
创建类别喜欢 UIViewController+Additions
File
-> New
-> File
Objective-C file
在 Sources
下在 iOS
然后点击下一步File Type:
选择Category
Additions
并设置类:UIViewController
UIViewController+Additions.h
首先在.h中创建你的后退按钮功能>>
-(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];
}
像这样使用:
只需在任何 View Controller 类中导入类别
#import "UIViewController+Additions.h"
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[self addBackButton];
}
关于ios - 我们如何在自定义 UIView 类中调用操作?需要在所有 View Controller 中重用 UIView 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36262168/