簡體   English   中英

如何子類 UITextField 並覆蓋 drawPlaceholderInRect 以更改占位符顏色

[英]How do I subclass UITextField and override drawPlaceholderInRect to change Placeholder color

我有一個帶有占位符文本集的 3 UITextField UITextField之一上,我希望占位符文本為紅色。

現在在谷歌搜索之后,似乎最好的方法是繼承 UITextField 並覆蓋drawPlaceholderInRect

我如何 go 關於子類化和覆蓋drawPlaceholderInRect 我沒有找到任何代碼示例或教程,而且我是 objective-c 和 iOS 開發的新手,所以發現它很難解決。

回答:

創建了一個名為CustomUITextFieldPlaceholder的新 objective-c class ,它是UITextField的子類。 CustomUITextFieldPlaceholder.m中放入以下代碼

 @implementation CustomUITextFieldPlaceholder

- (void)drawPlaceholderInRect:(CGRect)rect {
    // Set colour and font size of placeholder text
    [[UIColor redColor] setFill];
    [[self placeholder] drawInRect:rect withFont:[UIFont systemFontOfSize:12]];
}

@end

在您的項目中實現上述內容

#import "CustomUITextFieldPlaceholder.h"

IBOutlet CustomUITextFieldPlaceHolder *txtName;

注意:這行得通,我相信是正確的做法,但我還沒有完全測試過。 希望這個例子可以幫助其他人在我的情況下。

編輯:

改變了

[[UIColor redColor] setFill];

為了

[[UIColor colorWithRed:255.0 green:0.0 blue:0.0 alpha:0.7] setFill];

這樣我就可以將不透明度設置為 70% 以模仿默認占位符。

為了回答您的具體問題,這是子類化的工作方式:

// CustomTextField.h
@interface CustomTextField : UITextField {
}
@end

以下是如何覆蓋該方法:

@implementation
- (CGRect)placeholderRectForBounds:(CGRect)bounds {
    return CGRectMake(x,y,width,height);
}
@end

但是我認為這不是您要覆蓋的方法。 我想這就是你要找的:

@implementation
- (void)drawPlaceholderInRect:(CGRect)rect {
    // Your drawing code.
}
@end
[yourTextfield setValue:[UIColor colorWithRed:62.0/255.0f green:62.0/255.0f blue:62./255.0f alpha:1.0f]  forKeyPath:@"_placeholderLabel.textColor"];

我想這會有所幫助

子類化不會改變顏色。 我在這里提出了一項工作。

UITextField 占位符字體顏色 白色 iOS 5?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM