Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITextField custom background view and shifting text

I'm trying to use a custom textfield background. The problem is that the text then appears to be too close on the left.

I don't see any way to shift the text without subclassing UITextField. So I'm attempting to extend and overwrite

- (void)drawTextInRect:(CGRect)rect{
    NSLog(@"draw rect");
    CGRect newRect = CGRectMake(rect.origin.x+20,rect.origin.y,rect.size.width-20,rect.size.height);    
    [super drawTextInRect:newRect]; 
}

But for some reason the log never prints. I know the subclass is being used since I also have a log in the init, and that prints fine.

Whast goig on

EDIT.

I also try

- (CGRect)textRectForBounds:(CGRect)bounds{
    NSLog(@"bounds");
    CGRect b = [super textRectForBounds:bounds];
    b.origin.x += 20;
    return b;
}

That actually traces, but it doesn't seem to be shifting

like image 729
dizy Avatar asked Dec 08 '09 04:12

dizy


2 Answers

I think you could use the leftView property for this.

You can add a leftView and rightView to a UITextfield. These views can be used to display an icon, but if it's an empty view it'll just take up space, which is what you want.

CGFloat leftInset = 5.0f;
UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, leftInset, self.bounds.size.height)];
self.leftView = leftView;
self.leftViewMode = UITextFieldViewModeAlways;
[leftView release];
like image 185
Thomas Müller Avatar answered Oct 05 '22 09:10

Thomas Müller


Another Soultion:

In your appDelegate.m file write the following code at the top

@interface UITextField (myCustomTextField)

@end

@implementation UITextField (myCustomTextField)

- (CGRect)textRectForBounds:(CGRect)bounds {

    return CGRectInset(bounds, 10, 0);
}

- (CGRect)editingRectForBounds:(CGRect)bounds {
    return CGRectInset(bounds, 10, 0);
}

@end
like image 33
Jimit Avatar answered Oct 05 '22 10:10

Jimit