iOS 正在添加多个 CALayer,但只应用了一个
iOS multiple CALayers being added but only one gets applied
我想在我的文本字段中添加 left/right 边框。它是一个 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()
}
然后添加就好了..
您的问题在 ViewDidLoad
您需要在 viewDidLayoutSubviews
中设置此代码,因为它包含正确的框架
var once = true // as the function runs multiple times
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if once {
// here
once = false
}
}
我想在我的文本字段中添加 left/right 边框。它是一个 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()
}
然后添加就好了..
您的问题在 ViewDidLoad
您需要在 viewDidLayoutSubviews
中设置此代码,因为它包含正确的框架
var once = true // as the function runs multiple times
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if once {
// here
once = false
}
}