2012-07-18 83 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]; 

}

相關問題