【问题标题】:How to set an image of navigationbar every where in the app如何在应用程序的各处设置导航栏的图像
【发布时间】:2012-10-18 19:45:30
【问题描述】:

我正在使用情节提要构建一个应用程序。现在我希望在我的应用程序的每个屏幕上都有相同的 topBar/navigationbar。我想在这个导航栏上设置一个图像。经过一番搜索,我找到了这段代码。

@implementation UINavigationBar (CustomImage)
- (void)drawRect:(CGRect)rect
{
    UIImage *image = [UIImage imageNamed: @"topbar.jpg"];
    [image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}
@end  

我已将它放在我的 appdelagate.M 文件中的实施之上。但它不起作用。 还有人知道这是否也适用于 IOS 5.1?

亲切的问候。

【问题讨论】:

    标签: objective-c ios navigation storyboard


    【解决方案1】:

    看看UIAppearance。它允许您更改整个 UI 类的属性。例如,我在一个应用中有这个:

    UIImage *img = [UIImage imageNamed: @"NavBarBackground.png"];
    [[UINavigationBar appearance] setBackgroundImage:img forBarMetrics:UIBarMetricsDefault];
    

    UIAppearance 是在 iOS 5 中引入的。执行此操作的“旧”方法是使用相关类的类别(例如 UINavigationBar)覆盖 -drawRect:,就像您所做的那样。 (顺便说一下,“Swizzling”——将你的方法换成 SDK 提供的方法——不是必需的。)

    我发现,当 iOS5 出现时,drawRect 技巧不起作用,所以我必须有条件地使用UIAppearance,将上面的代码包含在if 语句中,如下所示:

    if ([[UINavigationBar class] respondsToSelector:@selector(appearance)]) {
        ...
    }
    

    为什么是有条件的?我们继续支持 iOS4,因此如果我们不对 UIAppearance 内容进行条件化,iOS4 用户将会遇到崩溃。因此,我们在应用中同时拥有这个和 drawRect 解决方案!

    如果您不必支持 iOS4,您绝对应该关注UIAppearance 以实现您的目标。

    【讨论】:

      【解决方案2】:

      我曾经为此调整 drawRect,您可以在 +initializemethod_exchangeImplementations (runtime.h) 执行调整。现在棘手的部分是调用原始的drawRect,因为方法被混合了,您需要使用自定义绘图方法name 来调用原始的。就像你画图一样,最后你会得到[super customDrawRect:rect];

      - (void)customDrawRect:(CGRect)rect { 
      
         ... 
         [super customDrawRect:rect];
      }
      

      #import <objc/runtime.h> 
      
      @implementation UINavigationBar (CustomImage)
      
      + (void)initialize {
      
          Method originalDrawRectMethod = class_getInstanceMethod([self class], @selector(drawRect:));
          Method customDrawRectMethod = class_getInstanceMethod([self class], @selector(customDrawRect:));
          method_exchangeImplementations(originalDrawRectMethod, customDrawRectMethod);
      }
      
      
      
      - (void)customDrawRect:(CGRect)rect {
      
          UIImage *image = [UIImage imageNamed: @"topbar.jpg"];
          [image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
      
          // original drawRect call
          [self customDrawRect:rect];
      }
      
      
      @end
      

      【讨论】:

      • 我很抱歉,但我不明白你在说什么。您是否有更详细的代码示例?
      • 我已经添加了代码,但您可以检查它,如果您发现并解决任何问题,请告诉我,以便我可以为其他人编辑文本。您可能会在 cocoadev.com/wiki/MethodSwizzling 上阅读有关 swizzling 的方法或寻找任何其他来源,有很多。
      • 谢谢,但它在 [self customImageDrawRect:rect] 上给出以下错误错误:“UINavigationBar”没有可见的@interface 声明选择器“customImageDrawRect:”
      • 哦对了,那是因为方法名是customDrawRect,缺少一个参数。
      猜你喜欢
      • 2015-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-11
      • 2014-04-25
      • 2019-10-21
      相关资源
      最近更新 更多