创建一个扩展
import Foundation
import UIKit
extension CALayer {
func addBorder(edge: UIRectEdge, color: UIColor, thickness: CGFloat) {
let border = CALayer()
switch edge {
case UIRectEdge.top:
border.frame = CGRect.zero
border.frame = CGRect(x: 0, y: 0, width: self.bounds.width, height: thickness)
break
case UIRectEdge.bottom:
border.frame = CGRect(x: 0, y: self.bounds.height - thickness, width: self.bounds.width, height: thickness)
break
case UIRectEdge.left:
border.frame = CGRect(x: 0, y: 0, width: thickness, height: self.bounds.height)
break
case UIRectEdge.right:
border.frame = CGRect(x: self.bounds.width - thickness, y: 0, width: thickness, height: self.bounds.height)
break
default:
break
}
border.backgroundColor = color.cgColor;
self.addSublayer(border)
}
}
并从控制器调用它们
someTextField.layer.addBorder(edge: UIRectEdge.bottom, color: UIColor.red, thickness: 2)
更新答案:创建一个新函数并添加宽度作为参数
func addBorder(edge: UIRectEdge, color: UIColor, thickness: CGFloat, width: CGFloat) {
let border = CALayer()
switch edge {
case UIRectEdge.top:
border.frame = CGRect(x: 0, y: 0, width: width, height: thickness)
break
case UIRectEdge.bottom:
border.frame = CGRect(x: 0, y: self.bounds.height - thickness, width: width, height: thickness)
break
case UIRectEdge.left:
border.frame = CGRect(x: 0, y: 0, width: thickness, height: self.bounds.height)
break
case UIRectEdge.right:
border.frame = CGRect(x: width - thickness, y: 0, width: thickness, height: self.bounds.height)
break
default:
break
}
border.backgroundColor = color.cgColor;
self.addSublayer(border)
}
之后,您必须为您的 TextField WIDTH 创建一个约束
并通过传递约束宽度来调用扩展,像这样
@IBOutlet weak var textFieldConstraintWidth: NSLayoutConstraint!
self.textField.layer.addBorder(edge: UIRectEdge.bottom, color: UIColor.red, thickness: 2, width: textFieldConstraintWidth.constant)