如何在UITextField子类中设置UITextField的属性

时间:2014-04-19 08:21:09

标签: objective-c uitextfield subclass uiappearance

我有UITextField的这个子类,我想设置一个属性作为UITextField的背景颜色,边框等。我不知道,如果我使用正确的方法,因为当我将这个类用于UItextField时,UITextField不会改变..在哪种方法中我必须声明这个属性?

#import "defaultUITextField.h"

@implementation defaultUITextField

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.delegate = self;
        [self setBackgroundColor:([UIColor redColor])];

        UIColor *borderColor = [UIColor colorWithRed:233.0/255.0 green:233.0/255.0 blue:233.0/255.0 alpha:233.0/255.0];

        self.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 5, 20)];
        self.leftViewMode = UITextFieldViewModeAlways;

        self.layer.borderColor = [borderColor CGColor];
        self.layer.borderWidth = 1.0f;
    }
    return self;
}

@end

1 个答案:

答案 0 :(得分:2)

你的解决方案似乎是正确的。 你是如何在视图上放置你的suctom TextField的? 如果您在Interface Builder中创建了TextField,那么您将覆盖错误的构造函数。

- (id)initWithCoder:(NSCoder *)inCoder {
    if (self = [super initWithCoder:inCoder]) {
        self.delegate = self;
        [self setBackgroundColor:([UIColor redColor])];

        UIColor *borderColor = [UIColor colorWithRed:233.0/255.0 green:233.0/255.0 blue:233.0/255.0 alpha:233.0/255.0];

        self.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 5, 20)];
        self.leftViewMode = UITextFieldViewModeAlways;

        self.layer.borderColor = [borderColor CGColor];
        self.layer.borderWidth = 1.0f;
    }
    return self;
}

在IB中创建UITextField并将其类更改为UItextField时,将调用此构造函数。