![](/img/trans.png)
[英]centering placeholder in the same UITextField, but of two different sizes
[英]Centering Placeholder Text in Subclass of UITextField
首先,我需要设置占位符文本颜色,因此我将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是我在初始化期间设置的属性。
伙伴们,伙计
子类化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
我认为这将工作(测试)
- (void) drawPlaceholderInRect:(CGRect)rect {
[[UIColor redColor] setFill];
[self.placeholder drawInRect:rect
withFont:self.font
lineBreakMode:UILineBreakModeTailTruncation
alignment:self.textAlignment];
}
https://github.com/mschulkind/cordova-true-native-ios/blob/master/Classes/UITextFieldPlugin.m
您可以在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];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.