UITextField set placeholder color as dark in iOS

前端 未结 8 765
误落风尘
误落风尘 2021-02-01 10:59

I have tried to set UITextField \"Placeholder\" color as dark.

NSAttributedString * search = [[NSAttributedString alloc] initWithSt         


        
8条回答
  •  花落未央
    2021-02-01 11:21

    As suggested by Apple, subclassing UITextField and overriding - (void)drawPlaceholderInRect:(CGRect)rect is the way to go:

    - (void)drawPlaceholderInRect:(CGRect)rect { 
        UIColor *colour = [UIColor lightGrayColor]; 
        if ([self.placeholder respondsToSelector:@selector(drawInRect:withAttributes:)]) 
        { // iOS7 and later 
            NSDictionary *attributes = @{NSForegroundColorAttributeName: colour, NSFontAttributeName: self.font}; 
            CGRect boundingRect = [self.placeholder boundingRectWithSize:rect.size options:0 attributes:attributes context:nil]; 
            [self.placeholder drawAtPoint:CGPointMake(0, (rect.size.height/2)-boundingRect.size.height/2) withAttributes:attributes]; } 
        else { // iOS 6 
            [colour setFill]; 
            [self.placeholder drawInRect:rect withFont:self.font lineBreakMode:NSLineBreakByTruncatingTail alignment:self.textAlignment]; 
        } 
     } 
    

    Credit: http://www.brightec.co.uk/blog/how-change-colour-uitextfields-placeholder-text-ios7-and-still-support-ios6

提交回复
热议问题