Placeholder text not centered for UITextField created programmatically

后端 未结 4 1945
粉色の甜心
粉色の甜心 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: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.

提交回复
热议问题