简体   繁体   中英

changing the layer.mask of a view doesn't update after the first time

I need a view to have rounded corners under certain conditions and regular square ones under others.

However, when I attempt to re-set the layer.mask of the view after its been set the first time, visually there is no change.

I first set the corners in the layoutSubviews method

- (void)layoutSubviews 
{

  // Create the mask image by calling the function
  UIImage *mask = MTDContextCreateRoundedMask( self.bounds, 10.0, 0.0, 10.0, 0.0 );
  // Create a new layer that will work as a mask
  CALayer *layerMask = [CALayer layer];
  layerMask.frame = self.bounds;
  // Put the mask image as content of the layer
  layerMask.contents = (id)mask.CGImage;
  // set the mask layer as mask of the view layer
  self.layer.mask = layerMask;
}

then once a condition is met I call another method

- (void)resetCorners {

  // Create the mask image by calling the function
  UIImage *mask = MTDContextCreateRoundedMask( self.bounds, 0.0, 0.0, 0.0, 0.0 );
  // Create a new layer that will work as a mask
  CALayer *layerMask = [CALayer layer];
  layerMask.frame = self.bounds;
  // Put the mask image as content of the layer
  layerMask.contents = (id)mask.CGImage;
  // set the mask layer as mask of the view layer
  self.layer.mask = layerMask;
}

however there is no visual change. what do i need to do?

You should avoid modifying the view (or in this case the layer) hierarchy in layoutSubviews. I suggest creating a method like - (void)setRoundedCornersEnabled:(BOOL)roundedCornersEnabled that modifies the layers appropriately for creating the rounded or square effect.

Under most circumstances the only code you want in layoutSubviews is code to modify the frames of subviews, and no matter what layoutSubviews should work under all possible states of your view (in this case rounded corners enabled or not). UIKit frequently invokes layoutSubviews on its own, so you can't rely on having full control over when that method will be called.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM