3

I am using 5 to 7 UITextField on every UIViewController in my project. I want to set border width for all those. I know the code for changing UITextField border width:

textField.layer.borderWidth=2.0f;

But for each and every UITextField I need to do that. Is there any simple way to achieve that.

Bhavin Ramani
  • 3,221
  • 5
  • 30
  • 41
UdayM
  • 1,725
  • 16
  • 34

3 Answers3

1

U can Assign textField.layer.borderWidth=2.0f; in NSObject class then u can inherit the class whenever u need

fathima
  • 181
  • 12
1

You can use the category for making global setting for UITextField like following:

FOR CREATE CATEGORY check this answer: 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;
}

OUTPUT IS

enter image description here

Nitin Gohel
  • 49,482
  • 17
  • 105
  • 144
  • :: sorry i am new to iOS, even though i use your code. i think i should call the method for every textfield – UdayM Apr 05 '16 at 09:42
  • you dont need to call this method after create a category you just need to copy and past its h and m file my code no need to do anythings – Nitin Gohel Apr 05 '16 at 09:42
  • i added borderstyle for your code because i need UITextBorderStyleRoundedRect like this: - (void)setBorderForColor:(UIColor*)color width:(float)width radius:(float)radius borderStyle:(UITextBorderStyle)borderStyle . but border style is not changing – UdayM Apr 05 '16 at 11:03
0

A best way to create a class subclass of UITextField and write code for border width and colour like stuff in subclass.And give your textfield's super class to created class.You don't need to write code again and again.