ios – 垂直居中UITextField的attributionPlaceholder

前端之家收集整理的这篇文章主要介绍了ios – 垂直居中UITextField的attributionPlaceholder前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我目前无法在UITextField中垂直对齐一个attributionPlaceholder,我不知道为什么.

这就是我在做的事情:

self.addressBar = [[UITextField alloc] initWithFrame: CGRectMake(...)];
self.addressBar.backgroundColor = [UIColor whiteColor];
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 : [UIFont fontWithName:@"Gotham-BookItalic" size:14.0],}
 ];
self.addressBar.delegate = self;
self.addressBar.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
[self.view addSubview:self.addressBar];

以下是发生的事情:

很明显,这是因为UITextFieldLabel的高度比UItextField本身小10px,但我似乎无法改变它.

这只发生在使用attributionPlaceholder时;默认的占位符属性工作得很好.

有任何想法吗?

解决方法

使用NSParagraphStyle增加最小行高:
NSMutableParagraphStyle *style = [self.addressBar.defaultTextAttributes[NSParagraphStyleAttributeName] mutableCopy];
style.minimumLineHeight = self.addressBar.font.lineHeight - (self.addressBar.font.lineHeight - [UIFont fontWithName:@"Gotham-BookItalic" size:14.0].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],NSParagraphStyleAttributeName : style
                                         }
 ];

您还可以覆盖 – (CGRect)placeholderRectForBounds:(CGRect)边界; UITextField子类中的方法.

它很乱,但它的工作原理:)

猜你在找的iOS相关文章