我有一个 UIBarButtonItem 并且想以编程方式设置转到前一个 Controller 的操作(在我的例子中,我以前的 View 是一个 UITableViewController)。
下面是我目前用来制作条形按钮项目的代码,尽管该按钮还没有转到上一个 View 。
UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:@"Done"
style:UIBarButtonItemStyleDone target:nil action:nil];
UINavigationItem *item = [[UINavigationItem alloc] initWithTitle:@"Website"];
item.leftBarButtonItem = leftButton;
item.hidesBackButton = YES;
[myBar pushNavigationItem:item animated:NO];
最佳答案
在您的 Controller 中添加以下代码,在 - (void)viewDidLoad
函数中:
调用 [self addBackButtonWithTitle:@"back"];
如果你想自定义带有标题的后退按钮。
或 [self addBackButtonWithImageName:@"back_button_image_name"];
如果您想要带有图像的自定义后退按钮。
/**
* @brief set lef bar button with custom title
*/
- (void)addBackButtonWithTitle:(NSString *)title {
UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:title style:UIBarButtonItemStylePlain target:self action:@selector(backButtonPressed:)];
self.navigationItem.leftBarButtonItem = backButton;
}
/**
* @brief set left bar button with custom image (or custom view)
*/
- (void)addBackButtonWithImageName:(NSString *)imageName {
// init your custom button, or your custom view
UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
backButton.frame = CGRectMake(0, 0, 40, 22); // custom frame
[backButton setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
[backButton addTarget:self action:@selector(backButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
// set left barButtonItem with custom view
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
}
- (void)backButtonPressed:(id)sender {
[self.navigationController popViewControllerAnimated:YES];
}
关于ios - 使后退按钮以编程方式转到上一个 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21869480/