选择时更改自定义 UIView 背景 [英] Changing a custom UIView background when selected

查看:50
本文介绍了选择时更改自定义 UIView 背景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

最初创建视图时,它是一个randomColor.如果再次选择视图,我希望这种颜色保持不变.IE.再次选择时从颜色变为灰色,然后变为灰色.

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.

更改视图背景或以某种方式向我的自定义 UIView 添加覆盖层以使其变灰的最佳方法是什么?

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

推荐答案

我认为最好的做法是将 UIView 子类化.在您的子类标题中:

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

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

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

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

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

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

这篇关于选择时更改自定义 UIView 背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆