0

ユーザーがボタンを押すと進行し、ボタンが離されると停止するカスタム進行状況ビューを作成したいと考えています。空白のサブビューは進行状況の背景を表し、開始点として機能する正方形が描かれています。ボタンが離されるまで空白のビューが埋められるはずです。ボタンが離されるまでビューを埋め続けるにはどうすればよいですか?

これが私のコードです:

CGContextRef context=UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 2.0);
CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor);


CGRect square=CGRectMake(0, 0, 5, 9);
CGContextAddRect(context, square);
CGContextStrokePath(context);

CGContextSetFillColorWithColor(context, [UIColor blueColor].CGColor);


CGContextFillRect(context, square);

ビュー コントローラの ViewDidLoad で

    SeekBar *seek=[[SeekBar alloc]initWithFrame:CGRectMake(0, 320, 320, 9)];
    [self.view addSubview:seek];

私はコア グラフィックスの初心者です。これは正しいアプローチですか?

4

1 に答える 1

0

さて、あなたが言及したように、一定の進歩を遂げるコードがいくつかあります。本当にやりたいことは、進行状況に基づいて塗りつぶしの幅を調整することです。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
于 2013-09-07T14:27:02.450 に答える