垂直居中UITextField的attributionPlaceholder

Joã*_*ira 10 iphone objective-c ios

我目前无法在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];
Run Code Online (Sandbox Code Playgroud)

以下是发生的事情:

UITextFieldLabel小于其父级

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

这只发生在使用attributionPlaceholder时; 默认的占位符属性可以正常工作.

有任何想法吗?

kea*_*ean 17

使用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],
                                         NSFontAttributeName : [UIFont fontWithName:@"Gotham-BookItalic" size:14.0],
                                         NSParagraphStyleAttributeName : style
                                         }
 ];
Run Code Online (Sandbox Code Playgroud)

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

这很麻烦,但它的工作原理:)