在UITextField子类中居中占位符文本

5
首先,我需要设置占位文本的颜色,因此我按照几篇Stack Overflow帖子的示例对UITextfield进行了子类化。这很有效。以下是其中一个示例帖子:如何对UITextField进行子类化并覆盖drawPlaceholderInRect以更改占位符颜色
但是,当我尝试使用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是我在初始化期间设置的属性。
3个回答

5

小伙子,这里有您需要的内容。

通过子类化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

1
谢谢。为了完整起见:为了解决这个问题,我使用了“placeholderRectForBounds”方法。我在原问题的编辑中展示了代码,供任何感兴趣的人参考。 - Jomnipotent17

4

2

您可以在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];

}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接