将占位符文本居中在UITextField的子类中 [英] Centering Placeholder Text in Subclass of UITextField
问题描述
首先,我需要设置占位符文本颜色,因此我将UITextfield子类化为几个堆栈溢出帖子中显示的内容。这很好用。以下是此示例帖子:如何做我将UITextField子类化并覆盖drawPlaceholderInRect以更改占位符颜色。
So first, I needed to set the placeholder text color, so I subclassed the UITextfield as shown in several stack overflow posts. This works fine. Here is an example post of this: How do I subclass UITextField and override drawPlaceholderInRect to change Placeholder color.
但是,当我尝试使用 searchNameField.textAlignment = UITextAlignmentCenter;
它不再以占位符为中心。输入文本仍然处于中心位置。
But, when I try to use searchNameField.textAlignment = UITextAlignmentCenter;
It is no longer centering the placeholder. The input text is still centered fine.
那么,假设由于子类化而使居中不起作用,我必须按顺序添加到我的UITextField子类中占位符文本居中?
So then, assuming that the centering is not working because of the subclassing, what do I have to add to my UITextField subclass in order to have the placeholder text centered?
谢谢
修改
这是我用来解决这个问题的代码。这是放在我的UITextField的子类中。
Here is the code I used to solve this problem. This is placed inside my subclass of 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是我在初始化期间设置的属性。
Note that placeholdTextSize is a property that I set during initialization.
推荐答案
这里你好伙伴
子类化UITextField将完成工作:
subclassing UITextField will do the work:
// 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的子类中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!