UIBarButtonItem - 更改背景和删除文本

时间:2014-11-27 11:29:44

标签: ios xcode uinavigationbar uibarbuttonitem

我正在尝试更改导航栏中presentViewController中的完成按钮,我可以使用此功能更改背景:

[[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"nav_bg.png"] forBarMetrics:UIBarMetricsDefault];

现在,当更改完成按钮将其替换为图像时,图像会重复,并且完成文本会保留在那里。使用这个:

UIImage *doneBackgroundImage = [[UIImage imageNamed:@"back-home.png"]
                                            resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)];

            [[UIBarButtonItem appearance] setBackgroundImage:doneBackgroundImage
                                                    forState:UIControlStateNormal
                                                       style:UIBarButtonItemStyleDone
                                                  barMetrics:UIBarMetricsDefault];

这就是它的样子: enter image description here

我在这做错了什么?

1 个答案:

答案 0 :(得分:0)

STEP:1

创建一个UIButton并使用presentViewContoller中的initWithCustomView将其分配给UIBarButtomItem

UIImage *customImage = [UIImage imageNamed:@"yourCustomImage"];
UIButton *customButton = [UIButton buttonWithType:UIButtonTypeCustom];
backButton.frame = CGRectMake(0, 0, customImage.size.width, customImage.size.height);
[backButton setImage:[UIImage imageNamed:@"yourCustomImage"] forState:UIControlStateNormal];
[backButton addTarget:self action:@selector(showPreviousView) forControlEvents:UIControlEventTouchUpInside];

UIBarButtonItem *leftBarButton = [[UIBarButtonItem alloc]initWithCustomView:customButton];

STEP:2

您可以从SO POST

中找到更多信息
 viewController.navigationItem.titleView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"yourimage.png"]];
    UIBarButtonItem * item = [[UIBarButtonItem alloc] initWithCustomView:[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"yourimage2.jpg"]]];    
    viewController.navigationItem.rightBarButtonItem = item;