2011-06-11 92 views
1

如何在UITextField內繪製進度條?到目前爲止我已經測試了兩種方法。顯示UITextField對象內的進度條

1.添加一個UIProgressView對象作爲UITextField對象的子視圖。

UIProgressView* progressView = [[UIProgressView alloc] init]; 
[aUITextField addSubview:progressView]; 
progressView.progress = 0.5; 
[progressView release]; 

2.子類UITextfield和覆蓋drawRect:

- (id)initWithFrame:(CGRect)frame { 
    if ((self = [super initWithFrame:frame])) { 
     // Initialization code 
     [self setBackgroundColor:[UIColor clearColor]]; 
    } 
    return self; 
} 

- (void)drawRect:(CGRect)rect { 
    // Drawing code 
    [[UIColor orangeColor] setFill]; 
    [[UIBezierPath bezierPathWithOvalInRect:rect] fill]; 
} 

這兩種方法都不起作用。你看到這些方法有什麼問題嗎?我該如何做這項工作?

回答

2

我不確定將UIProgressView作爲UITextField對象的子視圖將很有用,因爲您無法更改進度視圖的框架。

子類似乎是正確的方法。這是我能想到的。檢查它對你是否有用。

ProgressField.h

@interface ProgressField : UITextField { 

} 

@property (nonatomic, assign) CGFloat progress; 
@property (nonatomic, retain) UIColor * progressColor; 

@end 

ProgressField.m

@implementation ProgressField 
@synthesize progress; 
@synthesize progressColor; 

- (void)setProgress:(CGFloat)aProgress { 
    if (aProgress < 0.0 || aProgress > 1.0) { 
     return; 
    } 

    progress = aProgress; 

    CGRect progressRect = CGRectZero; 
    CGSize progressSize = CGSizeMake(progress * CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds)); 
    progressRect.size = progressSize; 

    // Create the background image 
    UIGraphicsBeginImageContext(self.bounds.size); 
    CGContextRef context = UIGraphicsGetCurrentContext(); 

    CGContextSetFillColorWithColor(context, [UIColor clearColor].CGColor); 
    CGContextFillRect(context, self.bounds); 

    CGContextSetFillColorWithColor(context, [self progressColor].CGColor); 
    CGContextFillRect(context, progressRect); 

    UIImage * image = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 

    [super setBackground:image]; 
} 

- (void)setBackground:(UIImage *)background { 
    // NO-OP 
} 

- (UIImage *)background { 
    return nil; 
} 

- (id)initWithFrame:(CGRect)frame { 
    if ((self = [super initWithFrame:frame])) { 
     [self setBorderStyle:UITextBorderStyleBezel]; 
    } 
    return self; 
} 

這似乎並不與borderStyle組與UITextField s到工作UITextBorderStyleRoundedRect

+0

我嘗試使用您的代碼,但仍然沒有首選結果。我會報告結果,如果我得到正確的顯示 – monsabre 2011-06-15 08:20:43

+0

當然,你可以看看['這個樣本'](http://dl.dropbox.com/u/22783696/ProgressField.zip)。使用滑塊來模擬「進度」中的變化。 – 2011-06-15 08:31:57

+0

感謝aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa批次 – monsabre 2011-06-15 08:50:20

0

在這裏,我認爲你必須添加progressView作爲子視圖self.view,只需根據適合UITextField的大小設置progressView的框架,並使progressview的集中心爲UITextField的中心。希望它能幫助你。

1
UIProgressView* progressView = [[UIProgressView alloc] init]; 
progressView.frame = aUITextField.frame;// you can give even set the frame of your own using CGRectMake(); 
[aUITextField addSubview:progressView]; 
progressView.progress = 0.5; 
[progressView release]; 

設置progressview的框架。