UITextField边界只在swift底部

我想只在UITextField底部保留边框。 但我不知道我们如何能保持底部。

你能告诉我吗?

如果以编程方式创buildUITextField对象,此答案将完美工作。

注意:如果在Storyboard中创build了UITextField对象,则在Storyboard“属性”检查器中将其“ Border Style属性设置为“ None

下面的variablestextFieldUITextField控件的一个对象,其中下边框将被设置。

SWIFT代码:

 let border = CALayer() let width = CGFloat(2.0) border.borderColor = UIColor.darkGray.cgColor border.frame = CGRect(x: 0, y: textField.frame.size.height - width, width: textField.frame.size.width, height: textField.frame.size.height) border.borderWidth = width textField.layer.addSublayer(border) textField.layer.masksToBounds = true 

目标C代码:

 CALayer *border = [CALayer layer]; CGFloat borderWidth = 2; border.borderColor = [UIColor darkGrayColor].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; 

Xamarin代码:

  var border = new CALayer(); nfloat width = 2; border.BorderColor = UIColor.Black.CGColor; border.Frame = new CoreGraphics.CGRect(0, textField.Frame.Size.Height - width, textField.Frame.Size.Width, textField.Frame.Size.Height); border.BorderWidth = width; textField.Layer.AddSublayer(border); textField.Layer.MasksToBounds = true; 

编辑:

许多用户在自动布局方面遇到问题,有些人无法呈现UITextField的边框。 这是解决scheme:


如果你在viewDidLoad()方法的代码中写下下面的代码,你将不会得到textField的框架,所以边框将不能正确渲染。

为了得到正确的边框,覆盖viewDidLayoutSubviews()并在其中写入代码。

将所有子视图加载到视图后调用的viewDidLayoutSubviews()方法。

不要忘记,这个方法被多次调用,它不是ViewController生命周期的一部分,所以在使用这个时要小心。

如果你想在事先没有了解框架的 情况下进行分类,

Swift 4Swift 3.x

 extension UITextField { func setBottomBorder() { self.borderStyle = .none self.layer.backgroundColor = UIColor.white.cgColor self.layer.masksToBounds = false self.layer.shadowColor = UIColor.gray.cgColor self.layer.shadowOffset = CGSize(width: 0.0, height: 1.0) self.layer.shadowOpacity = 1.0 self.layer.shadowRadius = 0.0 } } 

从任何地方调用yourTextField.setBottomBorder() ,而不必确保帧是正确的。

结果如下所示:

样品

您可以创buildUITextField的子类,如下所示:

 class TextField : UITextField { override var tintColor: UIColor! { didSet { setNeedsDisplay() } } override func draw(_ rect: CGRect) { let startingPoint = CGPoint(x: rect.minX, y: rect.maxY) let endingPoint = CGPoint(x: rect.maxX, y: rect.maxY) let path = UIBezierPath() path.move(to: startingPoint) path.addLine(to: endingPoint) path.lineWidth = 2.0 tintColor.setStroke() path.stroke() } } 
  extension UITextField { func setBottomBorder(color:String) { self.borderStyle = UITextBorderStyle.None; let border = CALayer() let width = CGFloat(1.0) border.borderColor = UIColor(hexString: color)!.CGColor border.frame = CGRect(x: 0, y: self.frame.size.height - width, width: self.frame.size.width, height: self.frame.size.height) border.borderWidth = width self.layer.addSublayer(border) self.layer.masksToBounds = true } } 

然后就这样做:

 yourTextField.setBottomBorder(color: "#3EFE46") 

在这里输入图像说明

目标C

  [txt.layer setBackgroundColor: [[UIColor whiteColor] CGColor]]; [txt.layer setBorderColor: [[UIColor grayColor] CGColor]]; [txt.layer setBorderWidth: 0.0]; [txt.layer setCornerRadius:12.0f]; [txt.layer setMasksToBounds:NO]; [txt.layer setShadowRadius:2.0f]; txt.layer.shadowColor = [[UIColor blackColor] CGColor]; txt.layer.shadowOffset = CGSizeMake(1.0f, 1.0f); txt.layer.shadowOpacity = 1.0f; txt.layer.shadowRadius = 1.0f; 

迅速

  txt.layer.backgroundColor = UIColor.white.cgColor txt.layer.borderColor = UIColor.gray.cgColor txt.layer.borderWidth = 0.0 txt.layer.cornerRadius = 5 txt.layer.masksToBounds = false txt.layer.shadowRadius = 2.0 txt.layer.shadowColor = UIColor.black.cgColor txt.layer.shadowOffset = CGSize.init(width: 1.0, height: 1.0) txt.layer.shadowOpacity = 1.0 txt.layer.shadowRadius = 1.0 

你可以在类之外创build这个扩展,并用你想要的任何边界replace宽度 –

 extension UITextField { func setBottomBorder(borderColor: UIColor) { self.borderStyle = UITextBorderStyle.None self.backgroundColor = UIColor.clearColor() let width = 1.0 let borderLine = UIView(frame: CGRectMake(0, self.frame.height - width, self.frame.width, width)) borderLine.backgroundColor = borderColor self.addSubview(borderLine) } } 

然后将其添加到您的viewDidLoadreplaceyourTextField与您的UITextFieldvariables和任何颜色,你想在边界

 yourTextField.setBottomBorder(UIColor.blackColor()) 

这基本上在文本字段的底部添加了一个具有该颜色的视图。

我所做的是创build一个扩展到UITextField并添加一个devise器可编辑的属性。 将此属性设置为任何颜色都会将边框(底部)更改为该颜色(将其他边框设置为无)。

由于这也需要改变占位符的文本颜色,所以我也加到了扩展中。

  extension UITextField { @IBInspectable var placeHolderColor: UIColor? { get { return self.placeHolderColor } set { self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "", attributes:[NSForegroundColorAttributeName: newValue!]) } } @IBInspectable var bottomBorderColor: UIColor? { get { return self.bottomBorderColor } set { self.borderStyle = UITextBorderStyle.None; let border = CALayer() let width = CGFloat(0.5) border.borderColor = newValue?.CGColor border.frame = CGRect(x: 0, y: self.frame.size.height - width, width: self.frame.size.width, height: self.frame.size.height) border.borderWidth = width self.layer.addSublayer(border) self.layer.masksToBounds = true } } } 

在Swift上3.你可以创build一个扩展,然后添加你的视图类。

 extension UITextField { func setBottomBorder(borderColor: UIColor) { self.borderStyle = UITextBorderStyle.none self.backgroundColor = UIColor.clear let width = 1.0 let borderLine = UIView() borderLine.frame = CGRect(x: 0, y: Double(self.frame.height) - width, width: Double(self.frame.width), height: width) borderLine.backgroundColor = borderColor self.addSubview(borderLine) } } 

这些解决scheme都不符合我的期望。 我想inheritanceTextField,因为我不想一直手动设置边框。 我也想改变边界的颜色,例如一个错误。 所以这里是我的解决scheme:

 class CustomTextField: UITextField { var bottomBorder = UIView() override func awakeFromNib() { // Setup Bottom-Border self.translatesAutoresizingMaskIntoConstraints = false bottomBorder = UIView.init(frame: CGRect(x: 0, y: 0, width: 0, height: 0)) bottomBorder.backgroundColor = UIColor(rgb: 0xE2DCD1) // Set Border-Color bottomBorder.translatesAutoresizingMaskIntoConstraints = false addSubview(bottomBorder) bottomBorder.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true bottomBorder.leftAnchor.constraint(equalTo: leftAnchor).isActive = true bottomBorder.rightAnchor.constraint(equalTo: rightAnchor).isActive = true bottomBorder.heightAnchor.constraint(equalToConstant: 1).isActive = true // Set Border-Strength } } 

– – 可选的 – –

要改变颜色添加像这样的CustomTextField Class

 @IBInspectable var hasError: Bool = false { didSet { if (hasError) { bottomBorder.backgroundColor = UIColor.red } else { bottomBorder.backgroundColor = UIColor(rgb: 0xE2DCD1) } } } 

在创buildCustomTextField的实例后触发Error调用此方法

 textField.hasError = !textField.hasError 

在这里输入图像说明

希望它可以帮助别人;)

这里是@IBInspectable的swift3代码

创build一个新的文件cocoa触摸类Swift文件

 import UIKit extension UIView { @IBInspectable var cornerRadius: CGFloat { get { return layer.cornerRadius } set { layer.cornerRadius = newValue layer.masksToBounds = newValue > 0 } } @IBInspectable var borderWidth: CGFloat { get { return layer.borderWidth } set { layer.borderWidth = newValue } } @IBInspectable var borderColor: UIColor? { get { return UIColor(cgColor: layer.borderColor!) } set { layer.borderColor = newValue?.cgColor } } @IBInspectable var leftBorderWidth: CGFloat { get { return 0.0 // Just to satisfy property } set { let line = UIView(frame: CGRect(x: 0.0, y: 0.0, width: newValue, height: bounds.height)) line.translatesAutoresizingMaskIntoConstraints = false line.backgroundColor = UIColor(cgColor: layer.borderColor!) line.tag = 110 self.addSubview(line) let views = ["line": line] let metrics = ["lineWidth": newValue] addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|[line(==lineWidth)]", options: [], metrics: metrics, views: views)) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[line]|", options: [], metrics: nil, views: views)) } } @IBInspectable var topBorderWidth: CGFloat { get { return 0.0 // Just to satisfy property } set { let line = UIView(frame: CGRect(x: 0.0, y: 0.0, width: bounds.width, height: newValue)) line.translatesAutoresizingMaskIntoConstraints = false line.backgroundColor = borderColor line.tag = 110 self.addSubview(line) let views = ["line": line] let metrics = ["lineWidth": newValue] addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|[line]|", options: [], metrics: nil, views: views)) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[line(==lineWidth)]", options: [], metrics: metrics, views: views)) } } @IBInspectable var rightBorderWidth: CGFloat { get { return 0.0 // Just to satisfy property } set { let line = UIView(frame: CGRect(x: bounds.width, y: 0.0, width: newValue, height: bounds.height)) line.translatesAutoresizingMaskIntoConstraints = false line.backgroundColor = borderColor line.tag = 110 self.addSubview(line) let views = ["line": line] let metrics = ["lineWidth": newValue] addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "[line(==lineWidth)]|", options: [], metrics: metrics, views: views)) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[line]|", options: [], metrics: nil, views: views)) } } @IBInspectable var bottomBorderWidth: CGFloat { get { return 0.0 // Just to satisfy property } set { let line = UIView(frame: CGRect(x: 0.0, y: bounds.height, width: bounds.width, height: newValue)) line.translatesAutoresizingMaskIntoConstraints = false line.backgroundColor = borderColor line.tag = 110 self.addSubview(line) let views = ["line": line] let metrics = ["lineWidth": newValue] addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|[line]|", options: [], metrics: nil, views: views)) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[line(==lineWidth)]|", options: [], metrics: metrics, views: views)) } } func removeborder() { for view in self.subviews { if view.tag == 110 { view.removeFromSuperview() } } } 

}

并用下面的代码replace文件,你会得到这样的故事板属性检查器的选项

在这里输入图像说明

请享用 :)

**这里myTF是MT文本字段的出口**

  let border = CALayer() let width = CGFloat(2.0) border.borderColor = UIColor.darkGray.cgColor border.frame = CGRect(x: 0, y: self.myTF.frame.size.height - width, width: self.myTF.frame.size.width, height: self.myTF.frame.size.height) border.borderWidth = width self.myTF.layer.addSublayer(border) self.myTF.layer.masksToBounds = true 

您可以创build一个底部边界的图像,并将其设置为您的UITextField的背景:

  yourTextField.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"yourBorderedImageName"]]; 

或将borderStyle设置为none,并将行的图像与textfield完全等长。

你可以使用这个ORGANIZED ,也可以自定义这个扩展:

viewDidAppear中的一行实现 ”(以使帧大小正确):

 // Add layer in your textfield yourTextField.addLayer(.bottom).addPadding(.left) // Extension extension UITextField { enum Position { case up, bottom, right, left } // MARK: - Add Single Line Layer func addLayer(_ position: Position) -> UITextField { // bottom layer let bottomLayer = CALayer() // set width let height = CGFloat(1.0) bottomLayer.borderWidth = height // set color bottomLayer.borderColor = UIColor.white.cgColor // set frame // y position changes according to the position let yOrigin = position == .up ? 0.0 : frame.size.height - height bottomLayer.frame = CGRect.init(x: 0, y: yOrigin, width: frame.size.width, height: height) layer.addSublayer(bottomLayer) layer.masksToBounds = true return self } // Add right/left padding view in textfield func addPadding(_ position: Position, withImage image: UIImage? = nil) { let paddingHeight = frame.size.height let paddingViewFrame = CGRect.init(x: 0.0, y: 0.0, width: paddingHeight * 0.6, height: paddingHeight) let paddingImageView = UIImageView.init(frame: paddingViewFrame) paddingImageView.contentMode = .scaleAspectFit if let paddingImage = image { paddingImageView.image = paddingImage } // Add Left/Right view mode switch position { case .left: leftView = paddingImageView leftViewMode = .always case .right: rightView = paddingImageView rightViewMode = .always default: break } } }