Iphone 在UITextField子类中居中占位符文本
因此,首先,我需要设置占位符文本颜色,因此我对UITextfield进行了子类化,如几个堆栈溢出帖子中所示。这个很好用。以下是这篇文章的一个示例: 但是,当我尝试使用Iphone 在UITextField子类中居中占位符文本,iphone,ios5,xcode4,uitextfield,Iphone,Ios5,Xcode4,Uitextfield,因此,首先,我需要设置占位符文本颜色,因此我对UITextfield进行了子类化,如几个堆栈溢出帖子中所示。这个很好用。以下是这篇文章的一个示例: 但是,当我尝试使用searchNameField.textAlignment=UITextAlignmentCenter它不再居中占位符。输入文本仍然居中 那么,假设由于子类化,居中不起作用,我必须向UITextField子类添加什么才能使占位符文本居中 谢谢 编辑 下面是我用来解决这个问题的代码。这被放置在我的UITextField子类中 - (C
searchNameField.textAlignment=UITextAlignmentCenter代码>它不再居中占位符。输入文本仍然居中
那么,假设由于子类化,居中不起作用,我必须向UITextField子类添加什么才能使占位符文本居中
谢谢
编辑
下面是我用来解决这个问题的代码。这被放置在我的UITextField子类中
- (CGRect)placeholderRectForBounds:(CGRect)bounds
{
CGSize size = [[self placeholder] sizeWithFont:[UIFont fontWithName:@"Arial" size:placeholdTextSize]];
return CGRectMake( (bounds.size.width - size.width)/2 , bounds.origin.y , bounds.size.width , bounds.size.height);
}
请注意,placeholdTextSize是我在初始化过程中设置的属性。给你
子类化UITextField将完成以下工作:
// CustomTextField.h
@interface CustomTextField : UITextField {
}
@end
覆盖以下方法:
@implementation
- (CGRect)placeholderRectForBounds:(CGRect)bounds {
return CGRectMake(x,y,width,height);//Return your desired x,y position and width,height
}
- (void)drawPlaceholderInRect:(CGRect)rect {
//draw place holder.
[[self placeholder] drawInRect:rect withFont:[UIFont systemFontOfSize:12]];
}
@end
我认为这会起作用(经过测试)
您可以在UITextfield子类中执行此操作
- (void)drawPlaceholderInRect:(CGRect)rect {
[[UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.8] setFill];
[[self placeholder] drawInRect:rect withFont:[UIFont boldSystemFontOfSize:16.0] lineBreakMode:UILineBreakModeTailTruncation alignment:NSTextAlignmentCenter];
}谢谢。为了完整性:为了解决这个问题,我使用了“占位符rectforbounds”方法。我在原始问题中的编辑为感兴趣的任何人显示了代码。
- (void)drawPlaceholderInRect:(CGRect)rect {
[[UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.8] setFill];
[[self placeholder] drawInRect:rect withFont:[UIFont boldSystemFontOfSize:16.0] lineBreakMode:UILineBreakModeTailTruncation alignment:NSTextAlignmentCenter];