【问题标题】:Shadow can't be added in iOS 7iOS 7 无法添加阴影
【发布时间】:2014-01-13 07:09:20
【问题描述】:

目标是在导航控制器视图的左侧添加一条阴影线,当视图向右滑动时可以看到。

但相同的代码(版本 1 和 2)适用于 iOS 6 和 5。

所有代码都放在-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

版本 1

CALayer *navigationViewLayer = [[[self navigationController] view] layer];
CGPathRef path = [[UIBezierPath bezierPathWithRect:[[[self navigationController] view] bounds]] CGPath];
[navigationViewLayer setShadowPath:path];
[navigationViewLayer setShouldRasterize:YES]; // rasterize save the effort of drawing every time by caching
[navigationViewLayer setRasterizationScale:[[UIScreen mainScreen] scale]]; // Have to set rasterization scale for retina screen
[navigationViewLayer setMasksToBounds:NO];
[navigationViewLayer setShadowRadius:5.0f];
[navigationViewLayer setShadowOpacity:1.0f];
[navigationViewLayer setShadowColor:[[UIColor blackColor] CGColor]];
[navigationViewLayer setShadowOffset:CGSizeMake(0.0f, 0.0f)];

版本 2

CGRect screenBoundsRect = [[UIScreen mainScreen] bounds];
CGRect rect = CGRectZero;
rect.origin.x = -4; // SHADOW_LINE_WIDTH
rect.origin.y = 0;
rect.size.width = 4; // SHADOW_LINE_WIDTH
rect.size.height = screenBoundsRect.size.height;
UIImageView *shadowLineImageView = [[UIImageView alloc] initWithFrame:rect];
CAGradientLayer *gradient = [CAGradientLayer layer];
[gradient setFrame:[shadowLineImageView bounds]];
[gradient setStartPoint:CGPointMake(1.0, 0.5)]; // default to (0.5, 0.0)
[gradient setEndPoint:CGPointMake(0.0, 0.5)]; // default to (0.5, 1.0)
[gradient setColors:[NSArray arrayWithObjects:(id)[[UIColor colorWithRed:140/255.f green:140/255.f blue:140/255.f alpha:1.0f] CGColor],
                                              (id)[[UIColor colorWithRed:189/255.f green:189/255.f blue:189/255.f alpha:0.0f] CGColor], nil]]; // color RGB values are optimized by test
[[shadowLineImageView layer] insertSublayer:gradient atIndex:0];
[shadowLineImageView setAlpha:1.0f];
[[[self navigationController] view] addSubview:shadowLineImageView];
[shadowLineImageView autorelease];

截图

图 1. 第 1 版适用于 iOS 6 模拟器:

图 2. 版本 1 适用于 iOS 5 iPhone 4:

图 3. 版本 1 不适用于 iOS 7 模拟器:

图 4. 第 2 版适用于 iOS 6 模拟器:

图 5. 第 2 版适用于 iOS 5 iPhone 4:

图 6. 版本 2 不适用于 iOS 7 模拟器:

【问题讨论】:

    标签: objective-c ios7 layer


    【解决方案1】:

    通过在 iOS 7、6 和 5 调用 [super viewDidLoad]; 后将上述代码(版本 1 和版本 2 都有效)放在 -(void)viewDidLoad 方法中的任何位置来解决。

    将上述代码放入- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 仅适用于 iOS 6 和 5。

    截图

    在调用[super viewDidLoad]; 后将上述代码放在-(void)viewDidLoad 方法中的任何位置时,

    版本 1 现在可在 iOS 7 模拟器上运行

    第 2 版现在可在 iOS 7 模拟器上运行

    【讨论】:

      猜你喜欢
      • 2014-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多