繁体   English   中英

占位符文本不以编程方式创建的UITextField为中心

[英]Placeholder text not centered for UITextField created programmatically

我正在以编程方式创建一个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];

感谢您的任何帮助

注意:我的意思是文本不是在文本字段中垂直居中(它有点朝向顶部)。 因此,设置文本对齐不是解决方案。

添加问题图像以便澄清 - 如图所示,占位符文本更靠近顶部而不是垂直居中。 替代文字

你需要添加:

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

请记住,这会调整占位符文本的对齐方式以及用户输入的文本。

如何垂直居中

由于原始问题已更新以请求如何垂直对齐占位符文本,并且该答案隐藏在注释中,以下是如何执行此操作:

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更改最小行高是唯一对我NSParagraphStyle的解决方案:

    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
}];

暂无
暂无

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

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