如何在iOS 7的UIExtField中添加带缩进的图像UIImage?

如何在iOS 7的UIExtField中添加带缩进的图像UIImage?,ios,objective-c,iphone,uiimage,uitextfield,Ios,Objective C,Iphone,Uiimage,Uitextfield,我有一个UITextField,我想在其中的左侧添加一个图像。我使用UITextField的leftView属性中设置的UIImageView执行此操作。在“图像视图”中将图像调整为适当大小。问题是它是粘在边界上的。如何设置图像的左缩进。我想一个解决方案是在图像的左侧设置一些空格,但我想使用缩进。我还想在图像后缩进一些,这样文本就不会离它太近了 我使用以下代码: [textField setLeftViewMode:UITextFieldViewModeAlways]; UIImageView

我有一个
UITextField
,我想在其中的左侧添加一个图像。我使用
UITextField
leftView
属性中设置的
UIImageView
执行此操作。在“图像视图”中将图像调整为适当大小。问题是它是粘在边界上的。如何设置图像的左缩进。我想一个解决方案是在图像的左侧设置一些空格,但我想使用缩进。我还想在图像后缩进一些,这样文本就不会离它太近了

我使用以下代码:

[textField setLeftViewMode:UITextFieldViewModeAlways];

UIImageView *imageView1 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 37, 20)];
imageView1.image = [UIImage imageNamed:@"custom_image"];
textField.leftView = imageView1;

您需要子类UITextField并在其中实现


-(CGRect)leftViewRectForBounds:(CGRect)bounds

也许您应该有一个子类UITextField和重写

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

这些将更改leftView的rect。

您可以将UIImageview帧设置为比原始UIImage更多的帧,并将UIImageview contentMode属性设置为centre。 请参考下面的答案

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;

将文本字段(无边框)放置在图像视图上,而不是子视图