如何更改 UINavigationBar 的背景?

发布于 2024-10-05 10:49:58 字数 165 浏览 7 评论 0原文

我想将 UINavigationBar 的背景更改为 [UIColor colorWithImage:],但它不起作用。我缺少什么?

编辑:

创建子类后,在哪里设置 UINavigationController 来使用它?

I'd like to change the background of my UINavigationBar to a [UIColor colorWithImage:], but it isn't working. What am I missing?

EDIT:

Once I've created my subclass, where do I set the UINavigationController to use it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

毅然前行 2024-10-12 10:49:58

您可以使用 tintColor 属性更改 UINavigationBar颜色,但要将图像设置为背景,您必须提供您的自己的 UINavigationBar 子类并重写 drawRect: 方法,例如:

- (void)drawRect:(CGRect)rect {
    // Drawing code 
    UIImage *img = [UIImage imageNamed: @"background-image.png"];
    [img drawInRect:CGRectMake(0, 
                               0, 
                               self.frame.size.width, 
                               self.frame.size.height)];
}

如果您使用 Interface Builder 构建 UI,然后要使用自定义导航栏,只需在Interface Builder,打开 Inspector 并在 Identity 选项卡中的类字段中指定 UINavigationBar 子类,如下所示:

显示自定义 UINavigationBar 的示例屏幕截图子类

You can use the tintColor property to change the colour of a UINavigationBar, but to set an image as the background you'll have to provide your own UINavigationBar subclass and override the drawRect: method, for example:

- (void)drawRect:(CGRect)rect {
    // Drawing code 
    UIImage *img = [UIImage imageNamed: @"background-image.png"];
    [img drawInRect:CGRectMake(0, 
                               0, 
                               self.frame.size.width, 
                               self.frame.size.height)];
}

If you use Interface Builder to build your UI then to use the custom navigation bar, just select the UINavigationBar element in Interface Builder, open the Inspector and in the Identity tab specify your UINavigationBar subclass in the class field, like so:

Example screenshot showing custom UINavigationBar subclass

甜妞爱困 2024-10-12 10:49:58

要在导航栏中显示图像,您必须自己绘制它,这实际上并不难。将其另存为 UINavigationBar+CustomBackground.m (它向 UINavigationBar 添加自定义类别):

@implementation UINavigationBar (CustomBackground)

- (void)drawRect:(CGRect)rect {
    UIImage *image = [UIImage imageNamed:@"NavMain.png"];
    [image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}

@end

To have an image in the navigation bar, you have to draw it yourself, which actually isn't that hard. Save this as UINavigationBar+CustomBackground.m (it adds a custom category to UINavigationBar):

@implementation UINavigationBar (CustomBackground)

- (void)drawRect:(CGRect)rect {
    UIImage *image = [UIImage imageNamed:@"NavMain.png"];
    [image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}

@end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文