Placeholder text not centered for UITextField created programmatically

后端 未结 4 1942
粉色の甜心
粉色の甜心 2020-12-08 04:14

I am creating a UITextField programmatically and placing it inside a UIView. The font size is set to 15.0f (system font). But the placeholder that appears is not centered in

相关标签:
4条回答
  • 2020-12-08 04:36

    You need to add:

    txtField.textAlignment = NSTextAlignmentCenter; // Pre-iOS6 SDK: UITextAlignmentCenter
    

    Keep in mind, this adjusts both the alignment of the placeholder text as well as the text the user will enter in.

    How to center vertically

    Since the original question was updated to request how to vertically align the placeholder text and that answer is buried in the comments, here is how to do that:

    txtField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    
    0 讨论(0)
  • 2020-12-08 04:40

    I was using just the color, but we need to set the font as well.

    This one worked for me:

    [[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setDefaultTextAttributes:
    @{
         NSForegroundColorAttributeName:[UIColor whiteColor], 
         NSFontAttributeName: [UIFont systemFontOfSize:12]
    }];
    
    0 讨论(0)
  • 2020-12-08 04:41

    Changing the minimum line height using NSParagraphStyle was the only solution that worked for me:

        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
    }];
    
    0 讨论(0)
  • 2020-12-08 04:47

    This does not work as expected on iOS7. On iOS7 you will have to override TextField class and

    - (void) drawPlaceholderInRect:(CGRect)rect
    

    method.

    Like this:

    - (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];
    }
    

    Works for both iOS7 and earlier versions.

    0 讨论(0)
提交回复
热议问题