ios - 如何使用图标向 UITextField 添加填充

标签 ios objective-c cocoa-touch uitextfield

我目前有以下代码来设置密码文本字段:

  self.passwordTextField = [UITextField new];
  self.passwordTextField.placeholder = @"Password";
  self.passwordTextField.font = [UIFont systemFontOfSize:18.f];
  self.passwordTextField.secureTextEntry = YES;
  self.passwordTextField.returnKeyType = UIReturnKeyDone;
  self.passwordTextField.delegate = self;
  self.passwordTextField.backgroundColor = [UIColor colorWithRed:255 green:255 blue:255 alpha:0.64];
  self.passwordTextField.layer.borderColor = [[UIColor lightGrayColor] CGColor];
  self.passwordTextField.layer.borderWidth = 1.0f;

  CGFloat textFieldHeight = 45.f;
  CGFloat textFieldWidth = 300.f;
  self.passwordTextField.frame = CGRectMake(DIALOG_VIEW_WIDTH/2.f - textFieldWidth / 2.f, 240.f, textFieldWidth, textFieldHeight);

  UIImageView *icon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"text-input-icon-password-key.png"]];
  icon.frame = CGRectMake(0, 0, 45.f, 45.f);
  icon.backgroundColor = [UIColor lightGrayColor];
  self.passwordTextField.leftView = icon;
  self.passwordTextField.leftViewMode = UITextFieldViewModeAlways;

  [self.dialogView addSubview:self.passwordTextField];

这给了我这个:

enter image description here

但是,我想在占位符文本的左侧和显示图标的 ImageView 的右侧添加一些更透明的填充。知道如何做到这一点吗?


更新:感谢您的回复。最后,我通过为整个对象创建一个 UIView,为图标创建一个 UIImageView,为文本创建一个嵌入另一个 UIView 的 UITextField 来实现这一点。结果如下:

enter image description here

最佳答案

更新:感谢您的回复。我最终通过为整个对象创建一个 UIView 并为图标创建一个 UIImageView 并为文本在另一个 UIView 中嵌入一个 UITextField 来实现这一点。

您可以继续使用 UITextFieldleftView 属性,例如:

UIView *vwContainer = [[UIView alloc] init];
[vwContainer setFrame:CGRectMake(0.0f, 0.0f, 50.0f, 45.0f)];
[vwContainer setBackgroundColor:[UIColor clearColor]];

UIImageView *icon = [[UIImageView alloc] init];
[icon setImage:[UIImage imageNamed:@"text-input-icon-password-key.png"]];
[icon setFrame:CGRectMake(0.0f, 0.0f, 45.0f, 45.0f)];
[icon setBackgroundColor:[UIColor lightGrayColor]];

[vwContainer addSubview:icon];

[self.passwordTextField setLeftView:vwContainer];
[self.passwordTextField setLeftViewMode:UITextFieldViewModeAlways];

关于ios - 如何使用图标向 UITextField 添加填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22326288/

相关文章:

ios - 无法识别的选择器发送到实例 Swift 2.1 - 日期选择器

ios - 如何使用 SKAction 循环播放音乐?

ios - 如何在一个许可证下同时使用笔记本电脑和台式机?

objective-c - 执行选择器 ARC 警告

objective-c - 当 NSTextField 的格式化程序更改格式时如何刷新?

objective-c - 当应用程序进入后台时继续下载

iphone - 获取时核心数据中的重复记录

iphone - 使用新目标将 IPA 上传到 TestFlight 时出错

ios - 如何在 subview Controller 中更改 iOS 状态栏颜色

ios - 我可以从 iOS 将 MP3 文件上传到我的服务器吗?