2014-09-23 48 views
10

我有一个UITextField其中我想在左侧添加图像。我使用UIImageView这是leftViewUITextField的财产设置。图像在图像视图中调整大小以适当大小。问题在于它坚持了边界。我如何设置图像的左缩进。我想一个解决方案是在图像的左侧设置一些空白区域,但我想使用缩进。我也想在图像后进行一些缩进,所以文字并不是那么接近。如何在iOS 7的UITextField中添加缩进图像UIImage?

我用下面的代码:

[textField setLeftViewMode:UITextFieldViewModeAlways]; 

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

代替子查看,将文本提交(无边框)放置在图像视图上 – raki 2014-09-23 10:45:35

回答

1

你需要继承的UITextField和执行它

- (CGRect)leftViewRectForBounds:(CGRect)bounds

1

也许你应该有一个子类的UITextField和覆盖

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

这些将改变leftView的矩形。

12

您可以设置比原始UIImage更多的UIImageview框架并将UIImageview contentMode属性设置为居中。 请参阅下面的答案。

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;