Строка-заполнитель UITextField всегда выравнивается по высоте в ios7
У меня есть подкласс класса UITextField и сделал код ниже
- (void)drawPlaceholderInRect:(CGRect)rect
{
[self.placeHolderTextColor setFill];
[self.placeholder drawInRect:rect
withFont:self.placeHolderFont
lineBreakMode:NSLineBreakByTruncatingTail
alignment:NSTextAlignmentLeft];
}
Я также написал
self.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;
строка кода
Этот текст заполнителя правильно выравнивается по центру в ios6, но не в ios7 отображается вверху.
Несмотря на то, что текст типа я отображается по центру. У него есть проблема с строкой-заполнителем.
Я попытался с помощью xib установить строку-заполнитель. В XIB он отображается правильно, но когда я запускаю текстовое поле кода, верхний выровненный.
Любое обходное решение для этого?
Ответ Вадоффа работал у меня. Тем не менее это полная реализация, которая может помочь любому, у кого есть такая же проблема.
drawInRect
метод устарел в ios7 и drawInRectWithAttributes
работает
- (void)drawPlaceholderInRect:(CGRect)rect
{
[self.placeHolderTextColor setFill];
CGRect placeholderRect = CGRectMake(rect.origin.x, (rect.size.height- self.placeHolderFont.pointSize)/2 - 2, rect.size.width, self.placeHolderFont.pointSize);
rect = placeholderRect;
if(iOS7) {
NSMutableParagraphStyle* style = [[NSMutableParagraphStyle alloc] init];
style.lineBreakMode = NSLineBreakByTruncatingTail;
style.alignment = self.placeHolderTextAlignment;
NSDictionary *attr = [NSDictionary dictionaryWithObjectsAndKeys:style,NSParagraphStyleAttributeName, self.placeHolderFont, NSFontAttributeName, self.placeHolderTextColor, NSForegroundColorAttributeName, nil];
[self.placeholder drawInRect:rect withAttributes:attr];
}
else {
[self.placeholder drawInRect:rect
withFont:self.placeHolderFont
lineBreakMode:NSLineBreakByTruncatingTail
alignment:self.placeHolderTextAlignment];
}
}
Ответы
Ответ 1
методы drawInRect, похоже, ведут себя по-разному в iOS7, вы можете попробовать добавить следующую строку и использовать ее как прямоугольник для рисования. Он также обратно совместим с pre-iOS7.
CGRect placeholderRect = CGRectMake(rect.origin.x, (rect.size.height- self.font.pointSize)/2, rect.size.width, self.font.pointSize);
Ответ 2
Ниже приведенный ниже код работает на iOS 5/6/7
@implementation PlaceholderTextField
- (void)drawPlaceholderInRect:(CGRect)rect
{
// Placeholder text color, the same like default
UIColor *placeholderColor = [UIColor colorWithWhite:0.70 alpha:1];
[placeholderColor setFill];
// Get the size of placeholder text. We will use height to calculate frame Y position
CGSize size = [self.placeholder sizeWithFont:self.font];
// Vertically centered frame
CGRect placeholderRect = CGRectMake(rect.origin.x, (rect.size.height - size.height)/2, rect.size.width, size.height);
// Check if OS version is 7.0+ and draw placeholder a bit differently
if (IS_IOS7) {
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
style.lineBreakMode = NSLineBreakByTruncatingTail;
style.alignment = self.textAlignment;
NSDictionary *attr = [NSDictionary dictionaryWithObjectsAndKeys:style,NSParagraphStyleAttributeName, self.font, NSFontAttributeName, placeholderColor, NSForegroundColorAttributeName, nil];
[self.placeholder drawInRect:placeholderRect withAttributes:attr];
} else {
[self.placeholder drawInRect:placeholderRect
withFont:self.font
lineBreakMode:NSLineBreakByTruncatingTail
alignment:self.textAlignment];
}
}
@end
Ответ 3
Я исправил эту проблему путем подкласса UITextFieldClass и переопределить функцию drawPlaceholderInRect.
- (void)drawPlaceholderInRect:(CGRect)rect
{
if(IS_IOS7)
{
[[self placeholder] drawInRect:CGRectMake(rect.origin.x, rect.origin.y+10, rect.size.width, rect.size.height) withFont:self.font];
}
else {
[[self placeholder] drawInRect:rect withFont:self.font];
}
}
Ответ 4
Небольшое обновление
- (void) drawPlaceholderInRect:(CGRect)rect {
if (self.useSmallPlaceholder) {
NSDictionary *attributes = @{
NSForegroundColorAttributeName : kInputPlaceholderTextColor,
NSFontAttributeName : [UIFont fontWithName:kInputPlaceholderFontName size:kInputPlaceholderFontSize]
};
//center vertically
CGSize textSize = [self.placeholder sizeWithAttributes:attributes];
CGFloat hdif = rect.size.height - textSize.height;
hdif = MAX(0, hdif);
rect.origin.y += ceil(hdif/2.0);
[[self placeholder] drawInRect:rect withAttributes:attributes];
}
else {
[super drawPlaceholderInRect:rect];
}
}
http://www.veltema.jp/2014/09/15/Changing-UITextField-placeholder-font-and-color/
Ответ 5
Почему бы просто не сдвинуть прямоугольник чертежа, а затем вызвать вызов реализации супер метода? Появляется быстрый код...
override func drawPlaceholderInRect(rect: CGRect) {
var newRect = CGRectInset(rect, 0, 2)
newRect.origin.y += 2
super.drawPlaceholderInRect(newRect)
}
Ответ 6
Потому что вы установили yourTextField.borderStyle = UITextBorderStyle....