ios - 如何创建自定义类以向 UINavigationBar IOS 添加阴影

标签 ios objective-c uinavigationbar shadow

我需要使用以下代码创建一个自定义类,以便在 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

我该怎么做?

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

最佳答案

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

您需要将类别更改为子类:

@interface CustomNavigationBar : UINavigationBar
...
@end

@implementation CustomNavigationBar
...
@end

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

UINavigationController *navController = [[UINavigationController alloc] initWithNavigationBarClass:[CustomNavigationBar class]
                                                                                      toolbarClass:nil];

// Make sure to provide a root view controller
[navController setViewControllers:@[rootViewController] animated:NO];

关于ios - 如何创建自定义类以向 UINavigationBar IOS 添加阴影,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31957170/

相关文章:

ios - 如何添加圆到矩形? UIBezierPath

objective-c - 适用于 iOS 的 GluUnProject

iphone - 如何检测删除按钮 UItableviewcell 是否被隐藏?

swift - 更喜欢单个 View Controller 的大标题

ios - 当在 UISearchBar 中粘贴搜索字段时,searchBar textDidChange 被调用两次

ios - itunes 连接不显示构建上传

ios - iOS后台信标监控

objective-c - 在 iPhone Simulator 4.3/XCode 4.2 和 4.0.2 中使用 Blocks 会导致应用程序崩溃

iphone - NSFetchedResultsController 中的 NSPredicate 抛出 EXC_BAD_ACCESS

ios - UINavigationBar 大标题重影