ios - 使后退按钮以编程方式转到上一个 View

标签 ios objective-c button

我有一个 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/

相关文章:

ios - Xcode失去了与iPhone 6的连接

html - 如何让我的 '<input type="提交“>”按钮更高

ios - 另一个 UItableviewCell 中的 UItableview

ios - iPhone 上的 UISplitViewController : pop to/show primary view from detail view controller

Android 按钮颜色在 onClick 上发生变化?

java - 按钮新游戏无法运行 Java

ios - iOS 是否允许将用户重定向到网站进行付款?

ios - 自动布局的视觉格式不适用于 iOS8

xcode - '(' 之前的预期标识符 'Synthesize"

iphone - UIImagePickerController 无法选择图片