好的,这里有一些代码可以按照你提到的那样不断进步。您真正想要做的是根据进度调整填充的宽度。看看这个drawRect:
方法。
此外,您希望将 SeekBar 连接到一个按钮,当有人按下按钮时,进度会增加/开始,当他们松开按钮时,进度会停止。调用的方法awakeFromNib:
应该会指导您。
如果您仍然对这段代码感到困惑,我可以发布示例项目,以便您可以构建和观察整个事情的协同工作。
SeekBar.h
#import <UIKit/UIKit.h>
@interface SeekBar : UIView
@property (nonatomic, strong) IBOutlet UIButton *button;
@end
SeekBar.m
#import "SeekBar.h"
@interface SeekBar()
@property (nonatomic) float progress;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) UILabel *completeLabel;
@end
@implementation SeekBar
- (void)awakeFromNib {
[self.button addTarget:self action:@selector(startProgress) forControlEvents:UIControlEventTouchDown];
[self.button addTarget:self action:@selector(stopProgress) forControlEvents:UIControlEventTouchUpInside];
}
- (void)startProgress {
if (![self.subviews containsObject:self.completeLabel]) {
[self addSubview:self.completeLabel];
}
self.progress = 0.0;
self.timer = [NSTimer scheduledTimerWithTimeInterval:0.001 target:self selector:@selector(incrementProgress) userInfo:nil repeats:YES];
}
- (void)incrementProgress {
if (self.progress <= 1.0) {
self.progress += 0.001;
[self setNeedsDisplay];
self.completeLabel.text = @"Loading...";
} else {
self.completeLabel.text = @"Complete";
}
}
- (UILabel *)completeLabel {
if (!_completeLabel) {
_completeLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, self.frame.size.width-10, self.frame.size.height)];
_completeLabel.backgroundColor = [UIColor clearColor];
_completeLabel.textColor = [UIColor whiteColor];
}
return _completeLabel;
}
- (void)stopProgress {
[self.timer invalidate];
}
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [UIColor blueColor].CGColor);
UIRectFill(CGRectMake(0, 0, rect.size.width * self.progress, rect.size.height));
}
@end