如何更改多个UITextField边框样式和颜色

时间:2014-01-14 01:27:41

标签: objective-c ios7 uitextfield uistoryboard uitextborderstyle

编辑#2

似乎基于我得到的回答,我混淆了人(以及随后的自己)。所以让我们试着简化一下这个问题 -

我希望给定ViewController以下的所有TextField:

textField.layer.cornerRadius=8.0f;
textField.layer.masksToBounds=YES;
[[textField layer] setBorderColor:[[UIColor colorWithRed:171.0/255.0 green:171.0/255.0 blue:171.0/255.0 alpha:1.0] CGColor]];
textField.layer.borderWidth= 1.0f;

我应该在哪里实现这个以及它如何不会给我层属性的错误(例如,当我尝试在-(void)viewDidLoad之后或之后执行此操作时,我会在每条行声明“属性”时收到错误在ViewController类型的对象上找不到图层?

编辑#1 完整的子类代码部分,以帮助确定问题:

@interface InputTextField : UITextField
@end
@implementation InputTextField

- (CGRect)textRectForBounds:(CGRect)bounds {
int margin = 5;
CGRect inset = CGRectMake(bounds.origin.x + margin, bounds.origin.y, bounds.size.width - margin, bounds.size.height);
return inset;
}

- (CGRect)editingRectForBounds:(CGRect)bounds {
int margin = 5;
CGRect inset = CGRectMake(bounds.origin.x + margin, bounds.origin.y, bounds.size.width - margin, bounds.size.height);
return inset;

InputTextField *textField=[[InputTextField alloc]init];
textField.layer.cornerRadius=8.0f;
textField.layer.masksToBounds=YES;
[[textField layer] setBorderColor:[[UIColor colorWithRed:171.0/255.0 green:171.0/255.0 blue:171.0/255.0 alpha:1.0] CGColor]];
textField.layer.borderWidth= 1.0f;
}

@end

原始帖子

我在更改特定视图控制器中一系列文本字段的边框样式和颜色时遇到问题。我想在视图中调整一堆文本字段。他们都被赋予了自定义类'InputTextField'。然而,在这个帖子中提出的解决方案:UITextField border color并没有解决我的问题。

这是我想要达到的风格和颜色:

textField.layer.cornerRadius=8.0f;
textField.layer.masksToBounds=YES;
[[textField layer] setBorderColor:[[UIColor colorWithRed:171.0/255.0 green:171.0/255.0 blue:171.0/255.0 alpha:1.0] CGColor]];
textField.layer.borderWidth= 1.0f;

我还导入了QuartzCore/QuartzCore.h。我想设置这个,以便我的应用程序中包含自定义类InputTextField的每个TextField都将以此背景显示。此时,每当我在应用程序中运行此字段时,字段都将采用我在故事板中设置的背景值(当前为无边框)。

感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

问题在于:

- (CGRect)editingRectForBounds:(CGRect)bounds {

return inset;

什么都没有被调用。将代码移到返回上方。

编辑#1

将此添加到您的子类:

- (void)layoutSubviews {
    CALayer *layer = self.layer;
    layer.cornerRadius = 8;
    layer.borderWidth = 1;
    layer.borderColor = [UIColor colorWithRed:171.0/255.0 green:171.0/255.0 blue:171.0/255.0 alpha:1.0].CGColor;
    [super layoutSubviews];
}

答案 1 :(得分:1)

你正在一个方法中实例化InputTextField只是要求你CGRect绘制一个矩形,这已经没有多大意义但是代码永远不会被调用,因为它位于之后return声明。

如果您希望所有InputTextField查看特定方式,请在layer实例化时设置InputTextField

使用如下所示的故事板:

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        self.layer.cornerRadius=8.0f;
        self.layer.masksToBounds=YES;
        [self.layer setBorderColor:[[UIColor colorWithRed:171.0/255.0 green:171.0/255.0 blue:171.0/255.0 alpha:1.0] CGColor]];
        self.layer.borderWidth= 1.0f;
    }
    return self;
}
相关问题