编辑时不显示UITextField阴影

con*_*dev 5 core-graphics objective-c uikit ios

我想在带有阴影的UITextField中绘制文本.为了做到这一点,我已经将UITextField子类化,并实现了drawTextInRect:如下方法:

- (void)drawTextInRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();

    // Create shadow color
    float colorValues[] = {0.21875, 0.21875, 0.21875, 1.0};
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGColorRef shadowColor = CGColorCreate(colorSpace, colorValues);
    CGColorSpaceRelease(colorSpace);

    // Create shadow
    CGSize shadowOffset = CGSizeMake(2, 2);
    CGContextSetShadowWithColor(context, shadowOffset, 0, shadowColor);
    CGColorRelease(shadowColor);

    // Render text
    [super drawTextInRect:rect];    
}
Run Code Online (Sandbox Code Playgroud)

这适用于文本字段未编辑时,但编辑开始后,阴影消失.有什么我想念的吗?

jak*_*eld 0

您可以尝试自己绘制标签。消除

[super drawTextInRect:rect]
Run Code Online (Sandbox Code Playgroud)

而是绘制自己的标签。我还没有尝试过,但它可能看起来像这样:

// Declare a label as a member in your class in the .h file and a property for it:
UILabel *textFieldLabel;
@property (nonatomic, retain) UILabel *textFieldLabel;

// Draw the label
- (void)drawTextInRect:(CGRect)rect {
    if (self.textFieldLabel == nil) {
        self.textFieldLabel = [[[UILabel alloc] initWithFrame:rect] autorelease];
        [self.view addSubview:myLabel];
    }

    self.textFieldLabel.frame = rect;
    self.textFieldLabel.text = self.text;

    /** Set the style you wish for your label here **/
    self.textFieldLabel.shadowColor = [UIColor grayColor];
    self.textFieldLabel.shadowOffset = CGSizeMake(2,2);
    self.textFieldLabel.textColor = [UIColor blueColor];

    // Do not call [super drawTextInRect:myLabel] method if drawing your own text
}
Run Code Online (Sandbox Code Playgroud)