Lê Khánh Vinh
Lê Khánh Vinh

Reputation: 2611

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

Upvotes: 1

Views: 1700

Answers (2)

KrishnaCA
KrishnaCA

Reputation: 5695

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

Upvotes: 1

neha mishra
neha mishra

Reputation: 374

You can put placeholder's "y" position means your "rect" value as a textfield height/2 .One more solution if you use default property of textfield for placeholder that would be horizontally aligned .

like as :

var tt : UITextField
        tt.placeholder = ""

Upvotes: 0

Related Questions