微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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子类中的方法.

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

原文地址:https://www.jb51.cc/iOS/328891.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐