Question

I have three custom circle UIViews which are created. When a user clicks on one of these I would like to change the background Color of the view to be Grey.

When the view is originally created, it is a randomColor. I would like this color to stay around for if the view was selected again. I.e. change from color to grey and then grey to color when selected again.

What is the best way to change the view background or add an overlay in someway to my custom UIView to make it grey?

Was it helpful?

Solution 2

I think the best think to do this is to subclass UIView. In your subclass header:

//MyCircleView.h
@interface MyCircleView : UIView
@end

In your implementation, use touchesDidBegin to toggle the background color when touches begin:

//MyCircleView.m
#import "MyCircleView.h

@interface MyCircleView()
@property (nonatomic) BOOL isSelected;
@end

@implementation MyCircleView

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    _isSelected = !_isSelected;

    //change background color
    self.backgroundColor = (_isSelected) ? [UIColor grayColor] : otherColor;
}

@end

If you want a shadow overlay, just change the code in the touchesBegan to toggle a UIView that can be added as a subview to the circle view:

//MyCircleView.m
#import "MyCircleView.h

@interface MyCircleView()
@property (nonatomic, strong) UIView *overlay;
@property (nonatomic) BOOL isSelected;
@end

@implementation MyCircleView

- (void)toggleOverlay {
    _isSelected = !_isSelected;

    //if overlay doesn't exist, create it
    if (!_overlay) {
        _overlay = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
        _overlay.backgroundColor = [UIColor colorWithWhite:0.0f alpha:0.4f]; //change overlay background alpha if you want it more/less transparent
        [_overlay setHidden:YES];
        [self addSubview:_overlay];
    }

    //show/hide overlay depending on selection
    [_overlay setHidden:!_isSelected];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self toggleOverlay];
}

@end

OTHER TIPS

One way to change a view's background when "selected" is having a subclass of the view and adding the touch events.

class CustomView: UIView {

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.backgroundColor = UIColor.selected
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.backgroundColor = UIColor.default
    }

    override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.backgroundColor = UIColor.default
    }
}

Subclass UIView and add properties for both colors.

You can add Touch Event when view is selected and change colors or add switch and set your view's backgroundColor's at him.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top