【问题标题】:Why does adding imageview to navigation bar in storyboard remove navbar?为什么将图像视图添加到故事板中的导航栏会删除导航栏?
【发布时间】:2013-08-07 16:58:03
【问题描述】:

我有一个工作应用程序,它是一个基于 tabbarcontroller 的应用程序。第一个 viewcontroller 是一个 uitableviewcontroller。所有 3 个选项卡的顶部都有一个导航栏,这是我从对象库中添加的。这是应用程序的外观:

然后我想将导航栏上的图像设置为居中的徽标。所以我环顾四周,发现代码看起来像这样:

 UIImage *image = [UIImage imageNamed:@"icon57.png"];
 UIImageView *imageView = [[UIImageView alloc] initWithImage: image];
 self.navigationItem.titleView = imageView;

[self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"icon57.png"] forBarMetrics:UIBarMetricsDefault];

但它没有工作。我刚得到一个空的白色导航栏。所以我决定通过从对象库中将 UIImageView 拖入导航栏来添加它,但由于某种原因,它使导航栏消失了,我最终得到了这个:

为什么会这样?

【问题讨论】:

    标签: ios uitableview uinavigationbar


    【解决方案1】:

    Interface Builder 不支持您的操作方式。我会鼓励你file a radar 支持这样做。您可以通过两种不同的方式来实现这一点,一种在代码中,另一种在 IB 中。

    通过界面生成器

    您可以将UIView 实例从对象库中拖放到导航栏的中心。这将在栏的标题区域内设置视图。然后,您可以获取 UIImageView 实例并将其添加为您刚刚添加的视图的子视图。

    通过代码

    您可以通过代码设置UIImageView,使用视图控制器导航项的titleView 属性:

    - (void)viewDidLoad {
        [super viewDidLoad];
    
        UIImage *logo = [UIImage imageNamed:@"logo.png"];
        self.navigationItem.titleView = [[UIImageView alloc] initWithImage:logo];
    }
    

    编辑:

    为了将其设置在左侧,您必须将图像视图包装在 UIBarButtonItem 中。您可以在 IB 中使用与上述相同的过程来执行此操作,也可以使用如下代码:

    - (void)viewDidLoad {
        [super viewDidLoad];
    
        UIImage *logo = [UIImage imageNamed:@"logo.png"];
        UIImageView *imageView = [[UIImageView alloc] initWithImage:logo];    
        UIBarButtonItem *imageButton = [[UIBarButtonItem alloc] initWithCustomView:imageView];
    
        self.navigationItem.leftBarButtonItem = imageButton;
    }
    

    【讨论】:

    • 好的,最后一件事。如何使它位于栏的左侧而不是中心?
    • 最后一个疑问,因为我将 UINavigationbar 放到了 UIViewController 上,它位于 uitabbarcontroller 中,为了使该代码正常工作,我需要先在代码中获取导航栏引用,对吧?
    • @marciokoko 您不应该将导航栏直接添加到您的视图控制器。您的视图控制器应嵌入在 UINavigationController 中,而后者又嵌入在 UITabBarController 中。
    • 好吧,我不需要栏的功能,只需要外观......在漂亮的栏中显示标题:) 我是否应该嵌入它而不使用该功能?
    猜你喜欢
    • 1970-01-01
    • 2010-12-05
    • 2012-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-09
    相关资源
    最近更新 更多