![](/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.