【问题标题】:CAGradientLayer - Doesn't cover the view completely in landscape orientationCAGradientLayer - 横向不完全覆盖视图
【发布时间】:2013-06-19 22:23:56
【问题描述】:

我使用this tutorial 为我的应用创建渐变背景。 它看起来很漂亮。但是,当我改变方向时会出现问题。

它在纵向模式下看起来不错,但在横向模式下,渐变不会覆盖整个视图。我已经上传了一个截图 -

红色是渐变,蓝色部分是默认的背景色,应该被红色渐变完全覆盖。

如何覆盖整个视图?在检测到旋转变化后,我尝试调用梯度方法,但没有成功。这是我使用的代码:

    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(deviceOrientationDidChangeNotification:)
     name:UIDeviceOrientationDidChangeNotification
     object:nil];// this is in 'viewWillAppear' method


- (void)deviceOrientationDidChangeNotification:(NSNotification*)note
{
    UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
    [self addBackground];
}

【问题讨论】:

  • 你的 addBackground 方法是什么样的?如果您使用的是教程gradient.frame = self.view.bounds; 中的代码,请确保您的 self.view.bounds 报告了正确的边界。
  • @DavisG。当方向改变时,如何在运行时获得正确的边界?
  • This 可能会有所帮助。看来-(void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation { 方法正确地报告了横向的边界。
  • 这对我来说是个新闻,但this 站点声明“在调用此方法时,基于视图(自身)边界的任何更改都不会更新。”它指的是 deviceOrientationDidChangeNotification
  • 我想知道为什么更新值需要这么长时间。无论如何 viewDidLayoutSubviews 工作正常。谢谢。

标签: iphone cagradientlayer


【解决方案1】:

我的猜测是系统发送UIDeviceOrientationDidChangeNotification实际更新横向布局的视图层次结构。

不要重做渐变以响应UIDeviceOrientationDidChangeNotification,而是在viewDidLayoutSubviews 中执行。当您的视图控制器收到viewDidLayoutSubviews 时,它的视图框架已经针对新的界面方向进行了修改。应该这样做:

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    self.background.frame = self.view.bounds;
}

【讨论】:

  • 这行得通,谢谢!当方向改变时,我使用 replaceSublayer 应用了一层新的渐变。 - stackoverflow.com/questions/3713292/replacesublayer-example 我不得不使用两种类似的方法。一个在 viewDidLoad 上绘制渐变,另一个用 viewDidLayoutSubviews 替换它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-04-20
  • 1970-01-01
  • 1970-01-01
  • 2014-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多