2012-07-18 57 views
5

首先,我需要设置占位符文本颜色,所以我将UITextfield分类为多个堆栈溢出帖子中显示的内容。这工作正常。以下是此示例的一个示例:How do I subclass UITextField and override drawPlaceholderInRect to change Placeholder color在UITextField的子类中居中放置占位符文本

但是,当我尝试使用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是我在初始化期间设置的属性。

回答

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 2012-07-18 11:31:16

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]; 

}

相关问题