Center align placeholder in textfield
You can center the placeholder by using an attributedPlaceholder
with a paragraph style whose alignment is set to .center
:
let centeredParagraphStyle = NSMutableParagraphStyle()
centeredParagraphStyle.alignment = .center
textField.attributedPlaceholder = NSAttributedString(
string: "Placeholder",
attributes: [.paragraphStyle: centeredParagraphStyle]
)
Create and connect IBOutlet to your textField. In YourViewController.m
@interface YourViewController () <UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *txt;
In your viewDidLoad
self.txt.delegate=self;
self.txt.textAlignment=NSTextAlignmentCenter;
Write this delegate method..this method calls everytime when text in text field changes.
- (BOOL) textField: (UITextField *)theTextField shouldChangeCharactersInRange: (NSRange)range replacementString: (NSString *)string {
NSRange textFieldRange = NSMakeRange(0, [self.txt.text length]);
// Check If textField is empty. If empty align your text field to center, so that placeholder text will show center aligned
if (NSEqualRanges(range, textFieldRange) && [string length] == 0) {
self.txt.textAlignment=NSTextAlignmentCenter;
}
else //else align textfield to left.
{
self.txt.textAlignment=NSTextAlignmentLeft;
}
return YES;
}
The answer by @Clay Ellis is correct, here it is for Objective-C:
UITextField* field = [[UITextField alloc] initWithFrame: fieldRect];
NSTextAlignment alignment = NSTextAlignmentCenter;
NSMutableParagraphStyle* alignmentSetting = [[NSMutableParagraphStyle alloc] init];
alignmentSetting.alignment = alignment;
NSDictionary *attributes = @{NSParagraphStyleAttributeName : alignmentSetting};
NSAttributedString *str = [[NSAttributedString alloc] initWithString:placeholder attributes: attributes];
field.attributedPlaceholder = str;