iOS添加了多个CALayers,但仅应用了一个

时间:2018-08-23 17:00:31

标签: ios swift calayer

我想在我的文本字段中添加一个左/右边框。它是一个IBOutlet。另外,如果我还添加了在didEdit委托回调内设置文本字段样式的函数,它将正确更新。

这是我的代码。在ViewDidLoad内部。

let leftLayer = CALayer()
    leftLayer.frame = CGRect(x: 0, y: 0, width: 1, height: (password.frame.size.height - 1))
    leftLayer.backgroundColor = UIColor.gray.cgColor

    let rightLayer = CALayer()
    rightLayer.frame = CGRect(x: password.frame.size.width - 1, y: 0, width: 1, height: (password.frame.size.height - 1))
    rightLayer.backgroundColor = UIColor.gray.cgColor

    password.layer.setNeedsDisplay()
    password.layer.addSublayer(leftLayer)
    password.layer.display()

    password.layer.setNeedsDisplay()
    password.layer.addSublayer(rightLayer)
    password.layer.display()

除了

,我已经取出了所有代码
  let rightLayer = CALayer()
    rightLayer.frame = CGRect(x: password.frame.size.width - 1, y: 0, width: 1, height: (password.frame.size.height - 1))
    rightLayer.backgroundColor = UIColor.gray.cgColor
    password.layer.setNeedsDisplay()
    password.layer.addSublayer(rightLayer)
    password.layer.display()

但是iOS根本不会添加此层。我尝试了下面的代码段

var once = true
override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    if once {
        styleTextViews()
        once = false
    }
}

唯一起作用的是如果我从

调用它
 func textFieldDidBeginEditing(_ textField: UITextField) {
    styleTextViews()
}

然后添加它就可以了。

1 个答案:

答案 0 :(得分:1)

您的问题出在ViewDidLoad中,您需要在viewDidLayoutSubviews内设置此代码,因为它包含正确的框架

var once  = true // as the function runs multiple times 

override func viewDidLayoutSubviews() {
  super.viewDidLayoutSubviews()
  if once {
   //  here 
    once = false
  }
}