Lê Khánh Vinh Lê Khánh Vinh - 28 days ago 19
Objective-C Question

IOS align text placeholder to be in the center and left alignment

I'm creating an IOS form that submits feed back.

I want to have placeholder text to be in the center vertically and left alignment horizontal in the text field

I have tried this

- (void)drawPlaceholderInRect:(CGRect)rect {
[RGB(36, 84, 157) setFill];

UIFont *font = [UIFont SingPostLightItalicFontOfSize:_placeholderFontSize fontKey:kSingPostFontOpenSans];
NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
paragraphStyle.alignment = NSTextAlignmentLeft;
NSDictionary *attributes = @{ NSFontAttributeName: font,
NSParagraphStyleAttributeName: paragraphStyle,
NSForegroundColorAttributeName: [UIColor blackColor]};
[[self placeholder] drawInRect:rect withAttributes:attributes];

}


But the place holder text is on top vertical. How can we achieve the gold. Thanks a lot

enter image description here

Answer

The following code will solve your problem. I tried it myself. It's just one additional line to your code.

- (void)drawPlaceholderInRect:(CGRect)rect {

       CGFloat fontSize = 18;
       UIFont *font = [UIFont systemFontOfSize:fontSize];
       NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
       paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
       paragraphStyle.alignment = NSTextAlignmentLeft;

       NSDictionary *attributes = @{ NSFontAttributeName: font,
                              NSParagraphStyleAttributeName: paragraphStyle,
       NSForegroundColorAttributeName: [UIColor blackColor]};

       CGRect newRect = CGRectInset(rect, 0, rect.size.height/2 - fontSize/2);
       [[super placeholder] drawInRect:newRect withAttributes:attributes];
}