在文本字段中居中对齐占位符 [英] Center align placeholder in textfield
本文介绍了在文本字段中居中对齐占位符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道这个问题曾多次被问过,但是我已经弃用了,我需要在ios 8中使用它。由于我有一个文本字段,我需要占位符在中心对齐并且测试的其余部分保持对齐。请帮助我。
I know this question been asked many times but as drawinrect deprecated and I need this in ios 8.As I have a textfield and I need the placeholder in center align and rest of the test left align.Please help me out.
推荐答案
创建IBOutlet并将其连接到textField。在 YourViewController.m
Create and connect IBOutlet to your textField. In YourViewController.m
@interface YourViewController () <UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *txt;
在 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;
}
这篇关于在文本字段中居中对齐占位符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文