CALayer 作为左边框不起作用?

CALayer as left border don´t working?

我在常规 ViewController 中有两个 UITextField,我用 CALayer 在左侧放置了一个绿色边框。

my textfield

这是我开发的代码:

let borderU = CALayer()
    let borderP = CALayer()

    let posx = CGFloat(2.0)

    let height:CGFloat = (txtfUser?.frame.size.height)!
    if #available(iOS 11.0, *) {
        borderU.borderColor = UIColor(named: "primaryGreen")?.cgColor
        borderP.borderColor = UIColor(named: "primaryGreen")?.cgColor
    } else {
        // Fallback on earlier versions
    }
    borderU.frame = CGRect(x: posx, y: -2, width:  2, height: height)
    borderP.frame = CGRect(x: posx, y: -2, width:  2, height: height)

    borderU.borderWidth = CGFloat(2.0)
    borderP.borderWidth = CGFloat(2.0)

    self.txtfUser?.layer.addSublayer(borderU)
    self.txtfUser?.layer.masksToBounds = true

    self.txtfPassWord?.layer.addSublayer(borderP)
    self.txtfPassWord?.layer.masksToBounds = true

在下一个视图控制器中,我有九个 UITextField,我需要在左侧使用相同的边框,我考虑过不要重复代码九次的解决方案,但没有奏效:

        let border = CALayer()

    let posx = CGFloat(2.0)

    let height:CGFloat = (txtfUser?.frame.size.height)!
    if #available(iOS 11.0, *) {
        border.borderColor = UIColor(named: "primaryGreen")?.cgColor
    } else {
        // Fallback on earlier versions
    }
    border.frame = CGRect(x: posx, y: -2, width:  2, height: height)

    border.borderWidth = CGFloat(2.0)

    self.txtfUser?.layer.addSublayer(border)
    self.txtfUser?.layer.masksToBounds = true

    self.txtfPassWord?.layer.addSublayer(border)
    self.txtfPassWord?.layer.masksToBounds = true

任何帮助将不胜感激。

您可以将您的 textField 子类化:

class TextField: UITextField {
    private var leftLayer: CALayer!
    override func awakeFromNib() {
        super.awakeFromNib()
        //create your layer here, and keep reference in leftLayer for further resize, color...
    }
}