UIView 子类有一个代码,它为您提供一个带有不透明圆形边框和中间透明孔的视图。您应该像往常一样创建所需的视图,然后您可以在视图上添加带有孔的视图。可视化在这里。
如果您为 UICollectionView 或 UITableView 使用单色背景,它可以工作,您可以为每个单元格添加以下子视图:
@interface TPRoundedFrameView : UIView
@property (assign, nonatomic) CGFloat cornerRadius;
@property (strong, nonatomic) UIColor * borderColor;
@end
@implementation TPRoundedFrameView
- (instancetype)init {
if ((self = [super init])) {
self.opaque = NO;
self.backgroundColor = [UIColor clearColor];
}
return self;
}
- (void)drawRect:(CGRect)rect {
[super drawRect:rect];
UIBezierPath * path = [UIBezierPath bezierPathWithRect:rect];
UIBezierPath * innerPath = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:self.cornerRadius];
[path appendPath:[innerPath bezierPathByReversingPath]];
[self.borderColor set];
[path fill];
}
@end
目标单元类示例:
- (void)awakeFromNib {
[super awakeFromNib];
// creating holed view with rounded corners
self.myRoundedView.backgroundColor = [UIColor whiteColor];
TPRoundedFrameView * roundedFrame = [TPRoundedFrameView new];
roundedFrame.cornerRadius = 5.f;
roundedFrame.borderColor = [UIColor groupTableViewBackgroundColor];
// add borders to your view with appropriate constraints
[self.myRoundedView addSubview:roundedFrame];
roundedFrame.translatesAutoresizingMaskIntoConstraints = NO;
NSDictionary * views = NSDictionaryOfVariableBindings(roundedFrame);
NSArray * horizontal = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[roundedFrame]-0-|" options:0 metrics:nil views:views];
NSArray * vertical = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[roundedFrame]-0-|" options:0 metrics:nil views:views];
[self.myRoundedView addConstraints:horizontal];
[self.myRoundedView addConstraints:vertical];
}
结果:
带有圆形视图的表格作为单元格