【问题标题】:How to create a custom class to add shadow to UINavigationBar IOS如何创建自定义类为 UINavigationBar IOS 添加阴影
【发布时间】:2015-08-12 06:05:21
【问题描述】:

我需要使用以下代码创建一个自定义类,以便在 iOS 中为 UINavigationBar 设置阴影。

@interface UINavigationBar (CustomImage)

-(void) applyDefaultStyle;

@end
@implementation UINavigationBar (DropShadow)
- (void)drawRect:(CGRect)rect {
    UIImage *image = [UIImage imageNamed: @"titleBar.png"];
    [image drawInRect:CGRectMake(0, 0, 320, 44)];
}

-(void)willMoveToWindow:(UIWindow *)newWindow{
    [super willMoveToWindow:newWindow];
    [self applyDefaultStyle];
}

- (void)applyDefaultStyle {
    // add the drop shadow
    self.layer.shadowColor = [[UIColor blackColor] CGColor];
    self.layer.shadowOffset = CGSizeMake(0.0, 3);
    self.layer.shadowOpacity = 0.25;
    self.layer.masksToBounds = NO;
    self.layer.shouldRasterize = YES;
}@end

我该怎么做?

此外,上面的代码为我的应用程序中的每个导航栏添加了阴影。如何控制这个?我只需要一两个导航栏上的阴影。

【问题讨论】:

    标签: ios objective-c uinavigationbar shadow


    【解决方案1】:

    每个UINavigationBar 都受到影响的原因是因为您的代码创建了一个category 并修改了现有的类。

    您需要将类别更改为子类

    @interface CustomNavigationBar : UINavigationBar
    ...
    @end
    
    @implementation CustomNavigationBar
    ...
    @end
    

    然后您可以使用UINavigationController initWithNavigationBarClass:toolbarClass: 并在您希望影响的导航控制器上提供CustomNavigationBar 类:

    UINavigationController *navController = [[UINavigationController alloc] initWithNavigationBarClass:[CustomNavigationBar class]
                                                                                          toolbarClass:nil];
    
    // Make sure to provide a root view controller
    [navController setViewControllers:@[rootViewController] animated:NO];
    

    【讨论】:

      【解决方案2】:

      您已经为 UINavigationBar 实现了 Category,这将影响所有 UINavigationBar 和它的自定义 UINavigationBar(UINavigationBar 的子类)。

      如果您希望仅在选定的导航栏上具有此行为,则可以采用 UINavigationBar 的继承(子类)。

      Take a look at this tutorial 1

      Tutorial 2

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-09-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-28
        • 1970-01-01
        相关资源
        最近更新 更多