UITextField与左视图对齐

时间:2014-02-27 15:29:05

标签: ios objective-c uitextfield alignment

我有一个UItextField,在leftView上有一个图像,但是我需要将UITextField与中心对齐,而在左视图中,它会向右移动。 下面是代码:

self.usernameField = [[UITextField alloc]initWithFrame:CGRectMake(0, 150, self.view.frame.size.width, 50)];
self.usernameField.placeholder = @"E-mail";
[self.usernameField setFont:[UIFont ralewayRegularFontWithSize:20]];
[self.usernameField setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
[self.usernameField setKeyboardType:UIKeyboardTypeEmailAddress];
[self.usernameField setBackground:[UIImage imageNamed:@"background_placeholder"]];
[self.usernameField setTextColor:[UIColor whiteColor]];
[self.usernameField setTextAlignment:NSTextAlignmentCenter];
[self.usernameField setAutocapitalizationType:UITextAutocapitalizationTypeNone];
[self.usernameField setBorderStyle:UITextBorderStyleNone];
[self.usernameField setBackgroundColor:[UIColor clearColor]];
[self.usernameField setLeftViewMode:UITextFieldViewModeAlways];
self.usernameField.leftView = [[UIView alloc] init];
[self.usernameField.leftView setFrame:CGRectMake(0, 0, 50, 30)];
[self.usernameField.leftView setBackgroundColor:[UIColor clearColor]];
UIImageView *imgViewMail = [[UIImageView alloc] initWithFrame:CGRectMake(20, 5, 25, 25)];
[imgViewMail setImage:[UIImage imageNamed:@"mail_icon"]];
[self.usernameField.leftView addSubview:imgViewMail];
[self.view addSubview:self.usernameField];

编辑 - 图像说明问题。 - 两个第一个textFields enter image description here

1 个答案:

答案 0 :(得分:0)

您可以创建自定义UITextField,并覆盖这些方法:

#pragma mark - Override UITextField

- (CGRect) textRectForBounds: (CGRect) bounds
{
  float x = bounds.origin.x + 50.f;
  float y = bounds.origin.y;
  float width  = bounds.size.width - (100.f);
  float height = bounds.size.height;

  return CGRectMake(x, y, width, height);
}

- (CGRect) editingRectForBounds: (CGRect) bounds
{
  return [self textRectForBounds: bounds];
}