我在我的項目中每使用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