简体   繁体   English

UITextField 背景图像在 iOS 中不起作用

[英]UITextField background image not working in iOS

I need to add background image in UITextField with left view mode also showing image.我需要在 UITextField 中添加背景图像,左视图模式也显示图像。 I have added both of them and its working.我已经添加了它们及其工作。 However my text content is stick to UITextField bottom.但是我的文本内容坚持 UITextField 底部。 I need to give space between textfield and content.我需要在文本字段和内容之间留出空间。

在此处输入图片说明

Below is my code with image.下面是我的带有图像的代码。

UITextField *textField = [UITextField new];
textField.borderStyle = UITextBorderStyleNone;
textField.background = [UIImage imageNamed:@"form-control.png"];
textField.translatesAutoresizingMaskIntoConstraints = NO;
textField.placeholder = @"Email/Phone no";
textField.font = [UIFont fontWithName:@"HelveticaNeue-Medium" size:16];

UIImageView *phoneImageView =[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 18, 21)];
phoneImageView.frame = CGRectInset(phoneImageView.frame, -5, 0);
[phoneImageView setImage:[UIImage imageNamed:@"phone.png"]];
[phoneImageView setContentMode:UIViewContentModeScaleAspectFit];
textField.leftView = phoneImageView;
textField.leftViewMode = UITextFieldViewModeAlways;

[self.view addSubview:textField];

you must set your textfield border-style square for keep image in your text-field as a background like this :您必须设置文本字段边框样式的正方形,以便将文本字段中的图像作为这样的背景:

For Square:-对于广场:-

    [textfield setBorderStyle:UITextBorderStyleLine];

For set background image用于设置背景图像

  [textField setBackground:[UIImage imageNamed:@"imagename.jpg"]];

In my projects I've solved this by using a UIImageView for the background of the textfield, and using auto-layout to attach the UIImageView frame to match the frame of the UITextField.在我的项目中,我通过使用 UIImageView 作为文本字段的背景解决了这个问题,并使用自动布局附加 UIImageView 框架以匹配 UITextField 的框架。 Once that's done, you can customize the margins between the textfield and the UIImageView by updating the constraints.完成后,您可以通过更新约束来自定义文本字段和 UIImageView 之间的边距。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM