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

Ste*_*lsh 3 cocoa-touch objective-c uitextfield ios

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

  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];
Run Code Online (Sandbox Code Playgroud)

这给了我这个:

在此输入图像描述

但是,我想在占位符文本的左侧和显示图标的图像视图的右侧添加一些更透明的填充.有什么想法可以做到这一点?


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

在此输入图像描述

sta*_*Man 14

" 更新:感谢您的回复.我最终通过为整个对象创建一个UIView来实现这一目标,其中包含用于图标的UIImageView和用于文本的另一个UIView中嵌入的UITextField. "

你可以继续使用这样的leftView属性UITextField:

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];
Run Code Online (Sandbox Code Playgroud)