如何为BackBarButton的左栏按钮创建自定义UIBarButton

时间:2014-01-16 06:47:16

标签: ios7 customization backbarbuttonitem

我正在尝试为iOS 7自定义应用程序的UI。我想要iOS 7的BackBarButton,但箭头和标题的颜色不同,标题的字体不同。这是iOS 7后退按钮。

BackBarButton of iOS 7

我尝试使用以下代码自定义

    UIImage *backButtonImage = [UIImage imageNamed:@"back.png"];
    UIButton *customBackButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [customBackButton addTarget:self action:@selector(backButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    [customBackButton setBackgroundImage:backButtonImage forState:UIControlStateNormal];
    [customBackButton setFrame:CGRectMake(0, 0, 30, 30)];       
    backButton = [[UIBarButtonItem alloc] initWithCustomView:customBackButton];
    [backButton setAction:@selector(backButtonPressed)];
    UIBarButtonItem * backButton = [[UIBarButtonItem alloc] initWithCustomView:customBackButton];

看起来像这样:

Customized BackBarButton

上面的图片存在两个问题。

首先它没有与左对齐(iOS后退按钮贴在左侧)。

其次,它没有上一页的标题。

我刚刚将自定义按钮添加了title属性。

    [customBackButton setTitle:@"title" forState:UIControlStateNormal];

但它是这样的:

customized backBarButton and it's title

如何解决问题(坚持左侧和标题)?

2 个答案:

答案 0 :(得分:0)

为此,您需要一个带箭头和图标的自定义图像。标题。 如果您想自定义标题,可以使用以下代码>

self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"My Title" style:UIBarButtonItemStylePlain target:nil action:nil];

但是如果你想要为图像设置它,你需要一个图像左侧有一个后退按钮。

图片:enter image description here

2x Image:enter image description here

在编辑器中查看图像,您可以注意到图像大小为70x32,箭头更靠左端。你也可以拥有带文字的图像&用它。

希望有所帮助。

答案 1 :(得分:0)

我刚刚发现了它是如何可能的

我写了下面的代码,它完美地运作了!

UIBarButtonItem * backButton = [UIBarButtonItem new];
UIView * backButtonView = [UIView new];
[backButtonView setFrame:CGRectMake(0, 0, 90, 32)];

UIImageView *backButtonImage = [UIImageView new];
[backButtonImage setImage:[UIImage imageNamed:@"Setting/back.png"]];
[backButtonImage setFrame:CGRectMake(-15, 0, 30, 30)];

UILabel * backButtonLabel = [UILabel new];
[backButtonLabel setFrame:CGRectMake(8, 0, backButtonView.frame.size.width, 30)];
[backButtonLabel setBackgroundColor:[UIColor clearColor]];
[backButtonLabel setTextColor:[UIColor whiteColor]];
[backButtonLabel setTextAlignment:NSTextAlignmentLeft];
[backButtonLabel setFont:[UIFont fontWithName:@"HelveticaNeue" size:18]];
[backButtonLabel setText:title];

UIButton *customBackButton = [UIButton buttonWithType:UIButtonTypeCustom];
[customBackButton addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
[customBackButton setFrame:CGRectMake(0, 0, 90, 30)];

[backButtonView addSubview:customBackButton];
[backButtonView addSubview:backButtonImage];
[backButtonView addSubview:backButtonLabel];

backButton = [[UIBarButtonItem alloc] initWithCustomView:backButtonView];
[backButton setAction:action];
[self.navigationItem setLeftBarButtonItem:backButton animated:YES];