更改多个UITextField的边框宽度

时间:2016-04-05 08:54:05

标签: ios objective-c uitextfield

我在项目的每个UITextField上使用5到7 UIViewController。我想为所有这些设置边框宽度。我知道更改UITextField边框宽度的代码:

textField.layer.borderWidth=2.0f;

但对于每一个UITextField我都需要这样做。有没有简单的方法来实现这一点。

3 个答案:

答案 0 :(得分:1)

你可以指定textField.layer.borderWidth = 2.0f;在NSObject类中,只要你需要

,你就可以继承该类

答案 1 :(得分:1)

您可以使用该类别为UITextField进行全局设置,如下所示:

  

FOR CREATE CATEGORY检查此答案:How to give padding to UITextField in iOS?

<强>的UITextField + setBorder.h

#import <UIKit/UIKit.h>

@interface UITextField (setBorder)


-(CGRect)textRectForBounds:(CGRect)bounds;
-(CGRect)editingRectForBounds:(CGRect)bounds;
- (void)setBorderForColor:(UIColor *)color
                    width:(float)width
                   radius:(float)radius;
@end

<强>的UITextField + setBorder.m

#import "UITextField+setBorder.h"

@implementation UITextField (setBorder)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-protocol-method-implementation"
-(CGRect)textRectForBounds:(CGRect)bounds {


     [self setBorderForColor:[UIColor redColor] width:5 radius:0];
    return CGRectMake(bounds.origin.x , bounds.origin.y ,
                      bounds.size.width , bounds.size.height );  // here you can make coercer position change
}
-(CGRect)editingRectForBounds:(CGRect)bounds {



    return [self textRectForBounds:bounds];
}


- (void)setBorderForColor:(UIColor *)color
                    width:(float)width
                   radius:(float)radius
{
    self.layer.cornerRadius = radius;
    self.layer.masksToBounds = YES;
    self.layer.borderColor = [color CGColor];
    self.layer.borderWidth = width;
}

输出

enter image description here

答案 2 :(得分:0)

创建UITextField的类子类并为子类中的东西编写边框宽度和颜色的代码的最佳方法。并将您的textfield超级类创建为class.You不需要编写代码一次又一次。

相关问题