我有一个UIBarButtonItem,并希望以编程方式设置前一个控制器的动作(在我的例子中,我以前的视图是一个UITableViewController)。
下面是我正在使用的代码来制作条形按钮项目,尽管该按钮尚未转到上一个视图。
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];
答案 0 :(得分:14)
在控制器的- (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];
}
答案 1 :(得分:10)
您可以在viewDidLoad
方法中写下这个:
UIBarButtonItem *btn=[[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStyleBordered target:self action:@selector(btnClick)];
self.navigationItem.leftBarButtonItem=btn;
然后使用它:
// call of method
-(void)btnClick
{
[self.navigationController popViewControllerAnimated:YES];
}
答案 2 :(得分:3)
[self dismissViewControllerAnimated:YES completion:nil];