我创建了一个自定义后退按钮(代码如下)。到目前为止,我一直在通过我的应用程序在每个页面上重新粘贴这段代码。我想知道是否有人可以以我的代码为例,并指导我如何将其放入一个集中位置,这样我就不必再复制和粘贴它了。
我猜这将进入我将创建的自定义类 .h 和 .m 中,但就代码本身在自定义文件中的样子而言,我不确定下一步该做什么。
// Create custom back button
UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *backButtonImage = [UIImage imageNamed"back.png"];
[backButton setBackgroundImage:backButtonImage
forState:UIControlStateNormal];
[backButton addTarget:self
actionselector(backButton)
forControlEvents:UIControlEventTouchUpInside];
[backButton setFrame:CGRectMake(0, 0, 40, 40)];
UIBarButtonItem *backButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
[[self navigationItem] setLeftBarButtonItem:backButtonItem];
我可能会使用 UIViewController
上的一个类别,其界面如下:
@interface UIViewController (MyBackButton)
- (void)installBackButtonWithActionSEL)action;
@end
实现是您问题中的代码,将 @selector(backButton)
替换为 action
:
#import "UIViewController+MyBackButton.h"
@implementation UIViewController (MyBackButton)
- (void)installBackButtonWithActionSEL)action {
UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *backButtonImage = [UIImage imageNamed"back.png"];
[backButton setBackgroundImage:backButtonImage
forState:UIControlStateNormal];
[backButton addTarget:self
action:action
forControlEvents:UIControlEventTouchUpInside];
[backButton setFrame:CGRectMake(0, 0, 40, 40)];
UIBarButtonItem *backButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
[[self navigationItem] setLeftBarButtonItem:backButtonItem];
}
@end
你可以这样调用它,例如:
- (void)viewDidLoad {
[super viewDidLoad];
[self installBackButtonWithActionselector(backButton)];
}
关于ios - 如何在 iOS 中为自定义后退按钮创建可重用代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17138223/
欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) | Powered by Discuz! X3.4 |