UITextField仅在Objective-C中具有底部边框

时间:2016-06-22 13:12:27

标签: ios objective-c uitextfield

我正在以编程方式创建UITextField,我正在尝试创建一个textField,其中只有底部边框,如图所示。请以编程方式在objective-c中帮助解决这个问题吗?

enter image description here

2 个答案:

答案 0 :(得分:8)

<强> 第一:

添加并导入QuartzCore框架。

#import <QuartzCore/QuartzCore.h>

<强> 第二

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;

<强> 编辑:

如果您有更多的TextFields,请创建一个常用方法,该方法需要UITextField并对其应用边框,如下所示:

-(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;

}

按如下方式传递TextField以设置Bottom Border:

[self SetTextFieldBorder:YourTextField];

答案 1 :(得分:1)

或者您可以在模拟边框的文本字段中添加细线子视图:

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版本:

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)