ash*_*Ios 7 placeholder uitextfield ios
我知道这个问题已被多次询问,但是我已经弃用了,我需要在ios 8中使用它.由于我有一个文本字段,我需要占位符在中心对齐并且测试的其余部分保持对齐.请帮助我.
Cla*_*lis 23
接受的答案方式使事情过于复杂......
通过使用attributedPlaceholder与段落样式结合使用,您可以将占位符置于中心位置UITextField.
let centeredParagraphStyle = NSMutableParagraphStyle()
centeredParagraphStyle.alignment = .center
let attributedPlaceholder = NSAttributedString(string: "Placeholder", attributes: [NSAttributedString.Key.paragraphStyle: centeredParagraphStyle])
textField.attributedPlaceholder = attributedPlaceholder
Run Code Online (Sandbox Code Playgroud)
创建IBOutlet并将其连接到textField.在YourViewController.m中
@interface YourViewController () <UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *txt;
Run Code Online (Sandbox Code Playgroud)
在你的viewDidLoad中
self.txt.delegate=self;
self.txt.textAlignment=NSTextAlignmentCenter;
Run Code Online (Sandbox Code Playgroud)
编写这个委托方法.每当文本字段中的文本发生变化时,此方法都会调用.
- (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;
}
Run Code Online (Sandbox Code Playgroud)
@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;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14033 次 |
| 最近记录: |