Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add image UIImage with indent in UITextField in iOS 7?

I have a UITextField in which I want to add an image on the left side. I do this using UIImageView which is set in leftView property of UITextField. The image is resized in Image View to proper size. The problem is that it is stick to the border. How can I set left indent of the image. I suppose that one solution is to set some blank space in the left side of the image, but I want to use indent. Also I want some indent after the image, so the text is not so close to it.

I use following code:

[textField setLeftViewMode:UITextFieldViewModeAlways];

UIImageView *imageView1 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 37, 20)];
imageView1.image = [UIImage imageNamed:@"custom_image"];
textField.leftView = imageView1;
like image 667
new2ios Avatar asked Sep 23 '14 10:09

new2ios


3 Answers

You can set the UIImageview frame more than the original UIImage and set the UIImageview contentMode property to centre. Please refer below answer.

UIImageView *imgSearch=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 32, 28)]; // Set frame as per space required around icon
[imgSearch setImage:[UIImage imageNamed:@"search.png"]];

[imgSearch setContentMode:UIViewContentModeCenter];// Set content mode centre

self.tfSearch.leftView=imgSearch;
self.tfSearch.leftViewMode=UITextFieldViewModeAlways;
like image 173
Pradhyuman Chavda Avatar answered Nov 11 '22 12:11

Pradhyuman Chavda


You need subclass UITextField and implement in it

- (CGRect)leftViewRectForBounds:(CGRect)bounds

like image 39
Cy-4AH Avatar answered Nov 11 '22 11:11

Cy-4AH


Maybe you should have a subclass UITextField and overrides

- (CGRect)leftViewRectForBounds:(CGRect)bounds;
- (void)drawTextInRect:(CGRect)rect;

These will change the rect for the leftView .

like image 1
Barry Wang Avatar answered Nov 11 '22 10:11

Barry Wang