代码之家  ›  专栏  ›  技术社区  ›  Geri Borbás

Calayers在其uiView的边界更改时没有调整大小。为什么?

  •  89
  • Geri Borbás  · 技术社区  · 16 年前

    我有一个 UIView 有8种不同的 CALayer 添加到其层的子层。 如果 我修改视图的边界 (动画),然后视图本身收缩(我用 backgroundColor ) 子层的大小保持不变 .

    如何解决这个问题?

    7 回复  |  直到 8 年前
        1
  •  129
  •   Chadwick Wood    16 年前

    我使用了与Solin相同的方法,但代码中有一个拼写错误。方法应为:

    - (void)layoutSubviews {
      // resize your layers based on the view's new bounds
      mylayer.frame = self.bounds;
    }
    

    出于我的目的,我一直希望子层是父视图的完整大小。将该方法放入视图类中。

        2
  •  24
  •   Ole Begemann    16 年前

    由于iPhone上的Calayer不支持布局管理器,我认为您必须使视图的主层成为一个自定义的Calayer子类,在其中您可以覆盖 layoutSublayers 设置所有子图层的帧。您还必须重写视图的 +layerClass 方法返回新calayer子类的类。

        3
  •  11
  •   Fattie    8 年前

    我在uiview里用过这个。

    -(void)layoutSublayersOfLayer:(CALayer *)layer
    {
        if (layer == self.layer)
        {
            _anySubLayer.frame = layer.bounds;
        }
    
    super.layoutSublayersOfLayer(layer)
    }
    

    为我工作。

        4
  •  9
  •   nschum Solin    13 年前

    我也有同样的问题。在自定义视图的图层中,我又添加了两个子图层。为了调整子图层的大小(每次自定义视图的边界更改时),我实现了该方法 layoutSubviews 我的自定义视图;在这个方法中,我只是更新每个子层的框架以匹配子视图层的当前边界。

    像这样:

    -(void)layoutSubviews{
       //keep the same origin, just update the width and height
       if(sublayer1!=nil){
          sublayer1.frame = self.layer.bounds;
       }
    }
    
        5
  •  4
  •   Ashish Gupta Vinay Krishna Gupta    9 年前

    斯威夫特3版

    在自定义单元格中,添加以下行

    先申报

    let gradientLayer: CAGradientLayer = CAGradientLayer()
    

    然后添加以下行

    override func layoutSubviews() {
        gradientLayer.frame = self.YourCustomView.bounds
    }
    
        6
  •  3
  •   Fattie    8 年前

    二千零一十七

    这个问题的字面回答是:

    “Calayers在其uiView的边界更改时没有调整大小。为什么?”

    是好是坏

    needsDisplayOnBoundsChange

    在中默认为false CALayer .

    解决方案,

    class CircularGradientViewLayer: CALayer {
    
        override init() {
    
            super.init()
            needsDisplayOnBoundsChange = true
        }
    
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    
        override open func draw(in ctx: CGContext) {
            go crazy drawing in .bounds
        }
    }
    

    事实上,我向你介绍这个质量保证

    https://stackoverflow.com/a/47760444/294884

    这就解释了,关键是什么? contentsScale 设置可以;您通常需要在设置needsDisplayBoundsChange时相等地设置它。

        7
  •  0
  •   DevGansta    11 年前

    正如[ole]所写,Calayer不支持在iOS上自动调整大小。所以您应该手动调整布局。我的选择是在(iOS 7及更早版本)内调整层的帧。

    - (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration 
    

    或(从iOS 8开始)

    - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id <UIViewControllerTransitionCoordinator>)coordinato