Ios 自动布局和底线文本字段
我为这些UITextField设置了如下约束 但是当我自定义文本字段时,它已经超出了约束Ios 自动布局和底线文本字段,ios,swift,Ios,Swift,我为这些UITextField设置了如下约束 但是当我自定义文本字段时,它已经超出了约束 emailTextField.backgroundColor = UIColor.clear emailTextField.attributedPlaceholder = NSAttributedString(string: emailTextField.placeholder!, attributes: [NSAttributedString.Key.foregroundColor: #
emailTextField.backgroundColor = UIColor.clear
emailTextField.attributedPlaceholder = NSAttributedString(string: emailTextField.placeholder!, attributes: [NSAttributedString.Key.foregroundColor: #colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1)])
emailTextField.borderStyle = .none
emailTextField.tintColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
let bottomLayer = CALayer()
bottomLayer.frame = CGRect(x: 0, y: 20, width: 1000, height: 0.7)
bottomLayer.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
emailTextField.layer.addSublayer(bottomLayer)
跑
请告诉我为什么?非常感谢……您已经设置了
CALayer
width 1000。它应该是文本字段的宽度
更改以下代码:
添加以下代码以获取emailTextField的更新帧并设置层的宽度:
emailTextField.setNeedsLayout()
emailTextField.layoutIfNeeded()
bottomLayer.frame = CGRect(x: 0, y: 20, width: emailTextField.frame.size.width, height: 0.7)
更新
如果要重用此textField配置,可以创建一个函数,如下所示:
func setupTextField(textField: UITextField) {
textField.backgroundColor = UIColor.clear
textField.attributedPlaceholder = NSAttributedString(string: textField.placeholder!, attributes: [NSAttributedString.Key.foregroundColor: #colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1)])
textField.borderStyle = .none
textField.tintColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
textField.setNeedsLayout()
textField.layoutIfNeeded()
let bottomLayer = CALayer()
bottomLayer.frame = CGRect(x: 0, y: 20, width: textField.frame.size.width, height: 0.7)
bottomLayer.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
textField.layer.addSublayer(bottomLayer)
}
您可以通过以下方式调用上述方法:
setupTextField(textField: textField)
这仍然是一个固定的宽度,当对实际的emailTextField
使用自动布局时,该宽度将被打破。为了在函数的参数中重用代码传递宽度,我有几个这样的文本字段,如何将此外观应用于所有这些字段,并多次写入几行代码?Thanks@VũTinhPhan为你工作的太好了。请点击我答案左边的勾号图标接受答案好吗?@iVarun没问题!它发生的宽度底层宽度请参考伊瓦伦回答。