UITextField placeholder string is always Top aligned in ios7

后端 未结 6 2673
滥情空心
滥情空心 2021-02-20 00:44

I have subclass the UITextField class and did the below code

- (void)drawPlaceholderInRect:(CGRect)rect
{

    [self.placeHolderTextColor setFill];
    [self.pl         


        
6条回答
  •  星月不相逢
    2021-02-20 01:14

    The code bellow works on 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
    

提交回复
热议问题