2013-08-30 43 views
0

我想要創建一個自定義進度視圖,該視圖在用戶按下按鈕時進行並在釋放按鈕時停止。 一個空白的子視圖代表了進度的背景,我畫了一個方塊作爲起點。 空白視圖應該被填充,直到按鈕被釋放爲止。如何繼續填充視圖直到按鈕被釋放?如何使用Core Graphics繪製進度視圖

這裏是我的代碼:

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]; 

我在覈心graphics.Is這種正確的做法是新手?

回答

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 
+0

難道這個不斷解決問題了嗎? –

相關問題