我在常规ViewController中有两个UITextField,我在左侧用CALayer设置了一个绿色边框。
这是我开发的代码:
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
在下一个View控制器中,我有九个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
任何帮助将不胜感激。
答案 0 :(得分:1)
您可以继承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...
}
}