- [UITextField drawPlaceholderInRect:]未被调用

时间:2014-07-30 18:06:40

标签: ios uitextfield

我正在开发一个应用程序,其中应该向用户提出建议,并且他可以接受或丢弃它。现在让我们说我只想向用户显示建议。

我正在使用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

重现的步骤:

  1. 点击文字字段
  2. 将field1.suggesting更改为true
  3. 点击文字字段并关闭键盘
  4. 文本字段中显示的文字应为绿色“abcde”

0 个答案:

没有答案