我正在开发一个应用程序,其中应该向用户提出建议,并且他可以接受或丢弃它。现在让我们说我只想向用户显示建议。
我正在使用drawTextInRect:
和drawPlaceholderInRect:
。
drawTextInRect:
按预期工作,但drawPlaceholderInRect:
仅被调用两次:首先出现文本字段,然后单击其中。之后,我猜它会缓存结果,并且不会再次调用drawPlaceholderinRect:
。
以下是示例代码:
#import <UIKit/UIKit.h>
#import "CustomTextField.h"
@interface ViewController : UIViewController
@property (weak, nonatomic) IBOutlet CustomTextField *field1;
@end
#import "ViewController.h"
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.field1.suggestionText = @"abcde";
}
- (IBAction)toggleSuggesting:(id)sender {
self.field1.suggesting = !self.field1.isSuggesting;
[self.field1 setNeedsDisplay];
}
@end
#import <UIKit/UIKit.h>
@interface CustomTextField : UITextField
@property(assign,nonatomic,getter=isRequired) BOOL required;
@property(assign,nonatomic,getter=isSuggesting) BOOL suggesting;
@property(strong,nonatomic) NSString* suggestionText;
@end
#import "CustomTextField.h"
@implementation CustomTextField
-(void)drawPlaceholderInRect:(CGRect)rect {
if ( _suggesting && [self.suggestionText length] > 0 ) {
[self drawSuggestionInRect:rect];
}
else {
[super drawPlaceholderInRect:rect];
}
}
-(void)drawTextInRect:(CGRect)rect {
if ( _suggesting && [self.suggestionText length] > 0 ) {
[self drawSuggestionInRect:rect];
}
else {
[super drawTextInRect:rect];
}
}
-(void)drawSuggestionInRect:(CGRect)rect {
[[UIColor greenColor] setFill];
[self.suggestionText drawInRect:rect withFont:self.font];
}
@end
重现的步骤: