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