我创建了三个自定义圈UIViews
。当用户点击其中一个时,我想将视图的背景颜色更改为灰色。
最初创建视图时,它是randomColor。如果再次选择视图,我希望这种颜色保持不变。即再次选择时,从颜色变为灰色,然后变为灰色。
更改视图背景或在我的自定义UIView中添加叠加层以使其变灰的最佳方法是什么?
答案 0 :(得分:6)
当“已选择”具有视图的子类并添加触摸事件时,更改视图背景的一种方法。
from datetime import datetime
from datetime import date
business_days_to_add = 5
holidays = [date(year=2009,month=12,day=25)]
for line in open("file.txt"):
print(workday(datetime.strptime(line.strip(), "%Y-%m-%d")), business_days_to_add, holidays)
答案 1 :(得分:1)
我认为最好的想法就是将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
答案 2 :(得分:0)
UIView子类并添加两种颜色的属性。
答案 3 :(得分:0)
您可以在选择视图时添加触摸事件并更改颜色或添加开关并将视图的backgroundColor设置为他。