【问题标题】:UITextField having bottom border only in Objective-CUITextField 仅在 Objective-C 中具有底部边框
【发布时间】:2016-10-24 11:02:05
【问题描述】:

我正在以编程方式创建UITextField,并且我正在尝试创建一个只有下边框的textField,如图所示。请以编程方式在 Objective-C 中解决这个问题?

【问题讨论】:

标签: ios objective-c uitextfield


【解决方案1】:

第一:

添加并导入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;

编辑:

如果您有更多的文本字段,请创建一种常用方法,该方法采用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 以设置底部边框:

[self SetTextFieldBorder:YourTextField];

【讨论】:

  • 如果我有 10 个文本字段,那么该怎么办?
【解决方案2】:

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

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-18
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-15
    相关资源
    最近更新 更多