Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to highlight a UIView like Apple does

When the user touches a UIButton it gets grayed-out a bit. What apple does to get such an effect? I need the same effect on my custom UIButton when it is highlighted.

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    AppDelegate* appDelegate=(AppDelegate*)[UIApplication sharedApplication].delegate;
    if ([keyPath isEqualToString:@"highlighted"]){
        UIButton *button = object;
        if (button.isHighlighted) {
            self.backgroundColor=[UIColor colorWithRed:36.0/255.0 green:153.0/255.0 blue:116.0/255.0 alpha:1];
        }else{
            self.backgroundColor=appDelegate.currentAppColor;
        }
    }
}

Im using this code, but changing background color wont affect any subviews. I need them to be grayed out too.

like image 306
t0a0 Avatar asked Jan 18 '14 22:01

t0a0


People also ask

What is a Uiview IOS?

An object that manages the content for a rectangular area on the screen.


1 Answers

You can use a custom view like this for example:

class HighlightView: UIView {

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        DispatchQueue.main.async {
            self.alpha = 1.0
            UIView.animate(withDuration: 0.4, delay: 0.0, options: .curveLinear, animations: {
                self.alpha = 0.5
            }, completion: nil)
        }
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        DispatchQueue.main.async {
            self.alpha = 0.5
            UIView.animate(withDuration: 0.4, delay: 0.0, options: .curveLinear, animations: {
                self.alpha = 1.0
            }, completion: nil)
        }
    }

    override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
        DispatchQueue.main.async {
            self.alpha = 0.5
            UIView.animate(withDuration: 0.4, delay: 0.0, options: .curveLinear, animations: {
                self.alpha = 1.0
            }, completion: nil)
        }
    }
}

Then you can use it instead of UIView and whenever you will click on it, it will change it's alpha value so it will look like a highlight.

like image 93
denis_lor Avatar answered Oct 19 '22 03:10

denis_lor