Darken view as if disabled

2019-04-12 01:43发布

How do you darken a view as if it were disabled/highlighted, preferably without using any additional views?

By view I mean a UIView, with all its children. I want to achieve the same effect of a disabled/highlighted UIButton.

Do not assume that the view is fully opaque.

3条回答
做个烂人
2楼-- · 2019-04-12 02:28

Example:

You have a UIButton *button1 and UIView *view1

You can disable a button and a view in this way:

[view1 setHidden:YES];
[button1 setEnabled:NO];

Enabling a button and a view can be done this way:

[view1 setHidden:NO];
[button1 setEnabled:YES];

Hope this helps..

查看更多
Animai°情兽
3楼-- · 2019-04-12 02:28

While this approach fails to meet your preference of not using additional views, simply adding a black view with alpha of 0.6 or so seems to achieve the effect, with the added benefit that you can use this new view to intercept UIEvents so that all the subviews are effectively disabled en masse.

You can even get graphically fancy and instead of just using a black background for the overlaid view, you can fill its background with a radial gradient to achieve the sort of spotlighted effect that happens in iOS when a popup view disables the view behind it...

查看更多
啃猪蹄的小仙女
4楼-- · 2019-04-12 02:38

What I'm currently playing with:

  1. Create a black layer with opacity (_highlightLayer). This is similar to the "black view with alpha" approach.
  2. Mask _highlightLayer with an non-opaque image of the original view.
  3. Add the _highlightLayer to the view's layer.

Only the non-transparent pixels of the view will be darkened.

The code:

- (void)highlight
{
    // Black layer with opacity
    _highlightLayer = [CALayer layer];
    _highlightLayer.frame = CGRectMake(0, 0, self.layer.bounds.size.width, self.layer.bounds.size.height);
    _highlightLayer.backgroundColor = [UIColor blackColor].CGColor;
    _highlightLayer.opacity = 0.5;

    // Create an image from the view        
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, 0.0);
    [self.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *maskImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    // Create a mask layer for the black layer 
    CALayer *maskLayer = [CALayer layer];
    maskLayer.contents = (__bridge id) maskImage.CGImage;
    maskLayer.frame = _highlightLayer.frame;

    _highlightLayer.mask = maskLayer;
    [self.layer addSublayer:_highlightLayer];
}

And then:

- (void)unhighlight
{
    [_highlightLayer removeFromSuperlayer];
    _highlightLayer = nil;
}

Of course, this should only be used for small views.

查看更多
登录 后发表回答