【问题标题】:Take away part of UIBarButton带走部分 UIBarButton
【发布时间】:2013-08-17 13:00:42
【问题描述】:

目前我有一个导航栏,上面有一个栏按钮,它是在我的故事板中创建的:

我想去掉条形按钮的白色部分,只保留图像。他们有办法做到这一点吗?

当我尝试这段代码时,没有条形按钮:

UIButton *btn =  [UIButton buttonWithType:UIButtonTypeCustom];
[btn setBackgroundImage:[UIImage imageNamed:@"19-gear.png"] forState:UIControlStateNormal];
UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithCustomView:btn];
self.navigationController.navigationBar.topItem.leftBarButtonItem = barButton;

【问题讨论】:

  • 显示创建条形按钮项的代码。
  • @rmaddy 我在我的故事板中创建了它。
  • 有没有办法将按钮的样式设置为“普通”而不是“边框”?无论如何,这将在代码中完成。
  • @rmaddy 你可以,但我收到警告说“导航项不支持纯文本”

标签: ios image uibarbuttonitem


【解决方案1】:
IButton *btn =  [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(5,5,60,34);
[btn setBackgroundImage:[UIImage imageNamed:@"19-gear.png"] forState:UIControlStateNormal];
UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithCustomView:btn];
self.navigationController.navigationBar.topItem.leftBarButtonItem = barButton;

你没有设置按钮的框架,为什么它没有出现在你的导航栏上。

【讨论】:

  • 是的,你的收获很好...... +1 给你。
【解决方案2】:

为什么不直接使用 CustomView?

UIBarButtonItem initWithCustomView:

然后您可以控制按钮(您必须为其提供图形)的确切显示方式。

Here's a related question 讨论如何设置自定义视图以响应点击。

编辑:

这里有一段代码在错误检查方面做得非常好,但我很确定在你的设置中有些地方不太对劲。使用它,我们也许能够找出它是什么。

UIButton *btn =  [UIButton buttonWithType:UIButtonTypeCustom];
if(btn)
{
    [btn setBackgroundImage:[UIImage imageNamed:@"19-gear.png"] forState:UIControlStateNormal];
    UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithCustomView:btn];
    if(barButton)
    {

        if(self.navigationController)
        {
            if(self.navigationController.navigationBar)
            {
                if(self.navigationController.navigationBar.topItem)
                {
                    self.navigationController.navigationBar.topItem.leftBarButtonItem = barButton;
                } else {
                    NSLog( @"why is topItem null?");
                }
            } else {
                NSLog( @"navigationBar appears to be null");
            }
        } else {
            NSLog( @"navigationController is null");
        }
    } else {
        NSLog(@"did not create UIBarButtonItem");
    }
} else {
    NSLog( @"did not create UIButton");
}

【讨论】:

  • 我应该使用什么作为自定义视图?
  • 您实际上可以将“UIButton”作为自定义视图。 :-) 看看上面链接问题中 ghazi_jaffary 的回答。
  • 谢谢,但是有没有办法在故事板中做到这一点?
  • 我不知道...要使用“initWithCustomView”,需要以编程方式完成。
  • 我怀疑大圆点参考线中的一项(例如“self.navigationController.navigationBar.topItem.leftBarButtonItem”)为零。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多