在文本字段中居中对齐占位符

我知道这个问题已被多次询问,但是我已经弃用了,我需要在ios 8中使用它。由于我有一个文本字段,我需要占位符在中心对齐,其余的测试左对齐。请帮助我。

创建IBOutlet并将其连接到textField。 在YourViewController.m中

@interface YourViewController ()  @property (weak, nonatomic) IBOutlet UITextField *txt; 

在你的viewDidLoad中

 self.txt.delegate=self; self.txt.textAlignment=NSTextAlignmentCenter; 

编写此委托方法。每当文本字段中的文本发生更改时,此方法都会调用此方法。

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

接受的答案方式使事情过于复杂……

通过使用与段落样式相结合的attributedPlaceholder ,您可以将占位符置于UITextField中心。

 let centeredParagraphStyle = NSMutableParagraphStyle() centeredParagraphStyle.alignment = .center let attributedPlaceholder = NSAttributedString(string: "Placeholder", attributes: [NSParagraphStyleAttributeName: centeredParagraphStyle]) textField.attributedPlaceholder = attributedPlaceholder 

@Clay Ellis的答案是正确的,这是针对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; 

基于Clay Ellis回答

细节

xCode 9.1,swift 4

 extension String { func attributedString(aligment: NSTextAlignment) -> NSAttributedString { return NSAttributedString(text: self, aligment: aligment) } } extension NSAttributedString { convenience init(text: String, aligment: NSTextAlignment) { let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.alignment = aligment self.init(string: text, attributes: [NSAttributedStringKey.paragraphStyle: paragraphStyle]) } } 

用法

 // Way 1 textField.attributedPlaceholder = text.attributedString(aligment: .center) // Way 2 textField.attributedPlaceholder = "title".attributedString(aligment: .center) // Way 3 textField.attributedPlaceholder = NSAttributedString(text: text, aligment: .left)