当被选中时改变自定义UIView背景



我已经创建了三个自定义圆UIViews。当用户单击其中一个时,我想将视图的背景颜色更改为灰色。

当视图最初创建时,它是一个随机颜色。如果再次选择视图,我希望这个颜色保持不变。也就是说,当再次选择时,从颜色变为灰色,然后从灰色变为颜色。

改变视图背景或以某种方式添加覆盖到我的自定义UIView使其成为灰色的最好方法是什么?

当"selected"时改变视图背景的一种方法是拥有视图的子类并添加触摸事件。

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
    }
}

我认为最好的方法是子类化UIView。在子类头文件中:

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

在你的实现中,当触摸开始时使用touchesDidBegin来切换背景颜色:

//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

如果你想要一个阴影覆盖,只需改变touchesBegan中的代码来切换一个UIView,它可以被添加为圆视图的子视图:

//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

子类UIView并为两种颜色添加属性

你可以在视图被选中时添加Touch Event并改变颜色,或者添加开关并设置视图的backgroundColor。

最新更新