iOS:为多个文本字段设置样式

时间:2014-03-14 22:13:01

标签: objective-c ios7

我有多个具有相同/相似样式的UITextField,但我会单独设置样式。我将如何设计它们?

我现在正在做的事情的例子:

textfield1.layer.borderWith = 2;
textfield2.layer.borderWith = 2;
textfield3.layer.borderWith = 2;

3 个答案:

答案 0 :(得分:0)

这是我过去使用过的东西:

UITextField * textField1;
UITextField * textField2;
UITextField * textField3;

for (UITextField * textField in @[textField1, textField2, textField3]) {
    textField.layer.borderWidth = 2;
}

如果您正在进行大量编辑以创建高度自定义的textField,那么使用子类可能会更好。如果您只想在每个文本字段中添加一些附加内容,那么这应该没问题。

根据您的要求,因为我感觉很慷慨。这是UITextField子类的示例。

MyTextField.h

#import <UIKit/UIKit.h>

@interface MyTextField : UITextField

@end

MyTextField.m

#import "MyTextField.h"

@implementation MyTextField

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.layer.borderWidth = 2;

        // Blue For Demonstration
        self.layer.borderColor = [UIColor blueColor].CGColor;

        // add whatever else you want to customize here ....
    }
    return self;
}

////////

////// ** Include Custom Methods You Might Need **

////////

@end

然后,无论您想使用哪个ViewController或View,请添加:

#import "MyTextField.h"

然后,您可以像这样启动MyTextField类Textfield:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    MyTextField * textField1 = [MyTextField new];
    textField1.frame = CGRectMake(10, 30, 100, 30);
    [self.view addSubview:textField1];

    MyTextField * textField2 = [MyTextField new];
    textField2.frame = CGRectMake(10, 70, 100, 30);
    [self.view addSubview:textField2];

    MyTextField * textField3 = [MyTextField new];
    textField3.frame = CGRectMake(10, 110, 100, 30);
    [self.view addSubview:textField3];
}

你会得到这个:

UITextField Subclass Demo

答案 1 :(得分:0)

怎么样 -

for (UIView *view in [self.view subviews]) {
    if ([view isKindOfClass:[UITextField class]]) {
        UITextField *textField = (UITextField *)view;
        textField.layer.borderWidth = 2.0;
    }
}

这样你甚至不必在视图中有textFields的出口。但是,这当然只适用于您希望将相同的样式应用于视图中的每个textField。

答案 2 :(得分:0)

如果文本字段有插座,请在.h中创建一个如此的IBOutletCollection:

@property (strong, nonatomic) IBOutletCollection(UITextField) NSArray *textFields;

然后,在你的.m:

-(void)viewWillAppear:(BOOL)animated {

    [super viewWillAppear:animated];

    for(UITextField *textField in self.textFields) {
        textfield.layer.borderWith = 2;
        // add more here as needed
    }
}