我可能只是将cornerRadius 应用于主进度视图以及显示进度的视图,而不是创建任何图像。所以,想象一下下面的视图层次结构:
主要的进度视图是后面的白色边框视图。它有一个子视图,progressSubview(上面以蓝色突出显示),它显示了迄今为止的进展(并且会随着我们更新 progress 属性而改变)。而绿色和蓝色视图只是固定大小的progressSubview 的子视图,显示为progressSubview,它剪切了它的子视图,改变了大小。
应用圆角半径非常容易。通过避免任何图像或自定义drawRect,我们可以根据需要对progressSubview 进行动画更改:
例如
// CustomProgressView.h
@import UIKit;
NS_ASSUME_NONNULL_BEGIN
IB_DESIGNABLE
@interface CustomProgressView : UIView
@property (nonatomic) CGFloat progress;
@end
NS_ASSUME_NONNULL_END
和
// CustomProgressView.m
#import "CustomProgressView.h"
@interface CustomProgressView ()
@property (nonatomic, weak) UIView *progressSubview;
@property (nonatomic, weak) UIView *greenView;
@property (nonatomic, weak) UIView *redView;
@end
@implementation CustomProgressView
- (instancetype)init {
return [self initWithFrame:CGRectZero];
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
if ((self = [super initWithCoder:aDecoder])) {
[self configure];
}
return self;
}
- (instancetype)initWithFrame:(CGRect)frame {
if ((self = [super initWithFrame:frame])) {
[self configure];
}
return self;
}
- (void)configure {
UIView *subview = [[UIView alloc] init];
subview.backgroundColor = [UIColor clearColor];
subview.clipsToBounds = true;
self.layer.borderColor = [[UIColor whiteColor] CGColor];
self.layer.borderWidth = 1;
UIView *redView = [[UIView alloc] init];
redView.backgroundColor = [UIColor redColor];
self.redView = redView;
UIView *greenView = [[UIView alloc] init];
greenView.backgroundColor = [UIColor greenColor];
self.greenView = greenView;
[self addSubview:subview];
[subview addSubview:redView];
[subview addSubview:greenView];
self.progressSubview = subview;
}
- (void)layoutSubviews {
[super layoutSubviews];
self.layer.cornerRadius = MIN(self.bounds.size.height, self.bounds.size.width) / (CGFloat)2.0;
self.progressSubview.layer.cornerRadius = MIN(self.bounds.size.height, self.bounds.size.width) / (CGFloat)2.0;
[self updateProgressSubview];
self.redView.frame = self.bounds;
CGRect rect = CGRectMake(self.bounds.origin.x, self.bounds.origin.y, self.bounds.origin.x + self.bounds.size.width / 2.0, self.bounds.origin.y + self.bounds.size.height);
self.greenView.frame = rect;
}
- (void)setProgress:(CGFloat)progress {
_progress = progress;
[self updateProgressSubview];
}
- (void)updateProgressSubview {
CGRect rect = CGRectMake(self.bounds.origin.x, self.bounds.origin.y, self.bounds.origin.x + self.bounds.size.width * self.progress, self.bounds.origin.y + self.bounds.size.height);
self.progressSubview.frame = rect;
}
- (void)prepareForInterfaceBuilder {
[super prepareForInterfaceBuilder];
self.progress = 0.75;
}
@end
然后你可以像这样更新进度:
[UIView animateWithDuration:0.25 animations:^{
self.progressView.progress = 0.75;
}];
...我在“UIView *”语义警告类型的对象上找不到属性“进度”
您的IBOutlet 似乎被定义为UIView 而不是CustomProgressView。