Строка-заполнитель 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];
    }

}

person Heena    schedule 30.09.2013    source источник
comment
У меня такая же проблема, решения пока нет.   -  person Vadoff    schedule 01.10.2013


Ответы (6)


Методы drawInRect, кажется, ведут себя по-разному в iOS7, вы можете попробовать добавить следующую строку и вместо этого использовать ее в качестве прямоугольника для рисования. Он также обратно совместим с версиями до iOS7.

  CGRect placeholderRect = CGRectMake(rect.origin.x, (rect.size.height- self.font.pointSize)/2, rect.size.width, self.font.pointSize);
person Vadoff    schedule 01.10.2013
comment
Одна небольшая проблема: вместо того, чтобы использовать pointSize шрифта, во многих случаях lineHeight вернет лучшие результаты для таких вещей, как центрирование, многострочный текст и т. д. Итак, в моем коде я использовал self.font.lineHeight везде, где вы использовать .pointSize - person sujal; 20.10.2013

Приведенный ниже код работает на 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
person Marius Kažemėkaitis    schedule 07.10.2013

Я исправил эту проблему, создав подкласс 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];
    }
}
person Muhammad Usman Aleem    schedule 29.11.2013

Небольшое обновление

- (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/

person Steven Veltema    schedule 15.09.2014

Почему бы просто не сдвинуть прямоугольник рисования, а затем вызвать вызов реализации суперметода? Получается код Swift...

override func drawPlaceholderInRect(rect: CGRect) {
    var newRect = CGRectInset(rect, 0, 2)
    newRect.origin.y += 2
    super.drawPlaceholderInRect(newRect)
}
person Gasper    schedule 23.12.2014

Поскольку вы установили yourTextField.borderStyle = UITextBorderStyle....

person giang.ngo    schedule 11.09.2015