[英]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.