I am creating UITextField programatically and i am trying to create a textField that has only bottom border as given in the figure. Please help this problem in objective-c programatically ?
            Asked
            
        
        
            Active
            
        
            Viewed 5,147 times
        
    5
            
            
         
    
    
        shubham mishra
        
- 971
- 1
- 13
- 32
- 
                    Possible duplicate of [UITextField border for bottom side only in swift](http://stackoverflow.com/questions/26800963/uitextfield-border-for-bottom-side-only-in-swift) – Adnan Aftab Jun 22 '16 at 13:39
2 Answers
9
            First:
Add and import QuartzCore framework.
#import <QuartzCore/QuartzCore.h>
Second:
CALayer *border = [CALayer layer];
CGFloat borderWidth = 2;
border.borderColor = [UIColor grayColor].CGColor;
border.frame = CGRectMake(0, textField.frame.size.height - borderWidth, textField.frame.size.width, textField.frame.size.height);
border.borderWidth = borderWidth;
[textField.layer addSublayer:border];
textField.layer.masksToBounds = YES;
EDIT:
If you have more TextFields, make one common method which takes UITextField and applies border to it like below:
-(void)SetTextFieldBorder :(UITextField *)textField{
    CALayer *border = [CALayer layer];
    CGFloat borderWidth = 2;
    border.borderColor = [UIColor grayColor].CGColor;
    border.frame = CGRectMake(0, textField.frame.size.height - borderWidth, textField.frame.size.width, textField.frame.size.height);
    border.borderWidth = borderWidth;
    [textField.layer addSublayer:border];
    textField.layer.masksToBounds = YES;
}
Pass your TextField as follows to set Bottom Border:
[self SetTextFieldBorder:YourTextField];
 
    
    
        Ronak Chaniyara
        
- 5,335
- 3
- 24
- 51
1
            
            
        Or you can add a thin line subview to the textfield that will mimic the border:
UIView *lineView = [[UIView alloc] init];
lineView.translatesAutoresizingMaskIntoConstraints = false;
lineView.backgroundColor = [UIColor grayColor];
[textField addSubview:lineView];
[lineView.heightAnchor constraintEqualToConstant:1];
[lineView.leftAnchor constraintEqualToAnchor:textField.leftAnchor constant:5.0];
[lineView.rightAnchor constraintEqualToAnchor:textField.rightAnchor constant:-5.0];
[lineView.bottomAnchor constraintEqualToAnchor:textField.bottomAnchor constant:0.0];
Swift version:
let lineView = UIView()
lineView.translatesAutoresizingMaskIntoConstraints = false
lineView.backgroundColor = UIColor.grayColor()
textField.addSubview(lineView)
lineView.heightAnchor.constraintEqualToConstant(1)
lineView.leftAnchor.constraintEqualToAnchor(textField.leftAnchor)
lineView.rightAnchor.constraintEqualToAnchor(textField.rightAnchor)
lineView.bottomAnchor.constraintEqualToAnchor(textField.bottomAnchor)
 
    
    
        marosoaie
        
- 2,352
- 23
- 32
