对于以编程方式创build的UITextField,占位符文本不居中

我正在创build一个UITextField编程,并将其放置在一个UIView。 字体大小设置为15.0f(系统字体)。 但是出现的占位符不在文本视图中居中。 任何人都知道如何解决这个问题?

我发现一些SO的模糊文本的参考和尝试设置整数值的文本框的框架,但没有什么区别。

UITextField *txtField = [[UITextField alloc] initWithFrame:CGRectMake(5.0f, 6.0f, 278.0f, 32.0f)]; [txtField setPlaceholder:@"My placeholder"]; [txtField setFont:[UIFont systemFontOfSize:15.0]]; [txtField setBorderStyle:UITextBorderStyleRoundedRect]; [txtField setAutocorrectionType:UITextAutocorrectionTypeNo]; [txtField setAutocapitalizationType:UITextAutocapitalizationTypeNone]; [txtField setKeyboardType:UIKeyboardTypeEmailAddress]; [txtField setReturnKeyType:UIReturnKeyDone]; [txtField setClearButtonMode:UITextFieldViewModeWhileEditing]; 

感谢您的任何帮助

注意:我的意思是文本在文本框中不是垂直居中的(有点朝上)。 所以设置文本alignment不是解决scheme。

添加一个问题的图像澄清 – 如图所示,占位符文本是更接近顶部,而不是垂直中心。 替代文字

你需要添加:

 txtField.textAlignment = NSTextAlignmentCenter; // Pre-iOS6 SDK: UITextAlignmentCenter 

请记住,这将调整占位符文本的alignment方式以及用户input的文本。

如何垂直居中

由于原来的问题已经更新,要求如何垂直alignment占位符文本,并将答案埋在评论中,下面是如何做到这一点:

 txtField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter; 

这在iOS7上无法正常工作。 在iOS7上,您将不得不重写TextField类和

 - (void) drawPlaceholderInRect:(CGRect)rect 

方法。

喜欢这个:

 - (void) drawPlaceholderInRect:(CGRect)rect { [[UIColor blueColor] setFill]; CGRect placeholderRect = CGRectMake(rect.origin.x, (rect.size.height- self.font.pointSize)/2, rect.size.width, self.font.pointSize); [[self placeholder] drawInRect:placeholderRect withFont:self.font lineBreakMode:NSLineBreakByWordWrapping alignment:self.textAlignment]; } 

适用于iOS7和更早版本。

我只是使用颜色,但我们也需要设置字体。

这个为我工作:

 [[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setDefaultTextAttributes: @{ NSForegroundColorAttributeName:[UIColor whiteColor], NSFontAttributeName: [UIFont systemFontOfSize:12] }]; 

使用NSParagraphStyle更改最小行高度是唯一适用于我的解决scheme:

  NSMutableParagraphStyle *style = [self.addressBar.defaultTextAttributes[NSParagraphStyleAttributeName] mutableCopy]; style.minimumLineHeight = self.addressBar.font.lineHeight - (self.addressBar.font.lineHeight - placeholderFont.lineHeight) / 2.0; self.addressBar.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"Placeholder text" attributes:@{ NSForegroundColorAttributeName: [UIColor colorWithRed:79/255.0f green:79/255.0f blue:79/255.0f alpha:0.5f], NSFontAttributeName : placeholderFont, NSParagraphStyleAttributeName : style }];