我在我的项目中每使用UIViewController
都使用5到7 UITextField
。我想为所有这些设置边框宽度。我知道改变UITextField
边框宽度代码:更改多个UITextFields的边框宽度
textField.layer.borderWidth=2.0f;
但对于每一个UITextField
我需要做的。有没有简单的方法来实现这一点。
我在我的项目中每使用UIViewController
都使用5到7 UITextField
。我想为所有这些设置边框宽度。我知道改变UITextField
边框宽度代码:更改多个UITextFields的边框宽度
textField.layer.borderWidth=2.0f;
但对于每一个UITextField
我需要做的。有没有简单的方法来实现这一点。
您可以使用类别进行全局设置为UITextField像以下:
FOR创建类别检查这个答案: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;
}
输出为
::对不起,我是新来的iOS,即使我使用你的代码。我想我应该调用每个文本域的方法 –
你不需要调用此方法后,创建一个类别,你只需要复制和过去其H和M文件我的代码不需要做任何事 –
我为你的代码添加边框,因为我需要UITextBorderStyleRoundedRect像这样: - (void)setBorderForColor :(UIColor *)color width:(float)width radius:(float)radius borderStyle:(UITextBorderStyle)borderStyle。但边框样式不变 –
U可以指定textField.layer.borderWidth = 2.0f;在NSObject类则u可以继承类每当u需要
创造的UITextField的类子类,并写了边框的宽度和颜色像子类的东西代码中的最佳途径。并给你的textfield的超类创建class.You不需要一次又一次地写代码。
扩展UITextField并使用该文本字段,无论你需要什么... –
为这样的定制创建一个UITextfield的类别 –
我同意@MuhammadAdnan,创建扩展名(或Objective-C中的类别)是最好的选择。 – TangZijian