我使用以下命令创建了一个带有底线的 UITextFiled:
let Bottomline CALayer = ()
bottomLine.frame CGRect = (x: 0, y: usernameTextField.frame.height-7, width: usernameTextField.frame.width, height: 1)
bottomLine.backgroundColor = UIColor.black.cgColor
TextField.borderStyle = UITextBorderStyle.none
TextField.layer.addSublayer (Bottomline)
iPhone 6(右)的结果是这样的:
好的。
✄------------------------
The problem is to run the same application on a Pro iPad, because the bottom line does not extend following the UITextField, but is shorter
这是 iPad Pro 上的结果:
我不明白为什么底线不遵循 UITextField。当我调用底线时,我定义为:
bottomLine.frame CGRect = (x: 0, y: usernameTextField.frame.height-7, width: usernameTextField.frame.width, height: 1)
我已指定底部线条的长度必须为:
width: usernameTextField.frame.width
问题是什么?
EDIT 1: The contrains are correct, because the UITextField adapts to all types of resolution
编辑:2 谢谢马特!现在开始工作吧!!!
最佳答案
I do not understand why the bottom line does not follow the UITextField
因为它是一个层。当其 super 图层(文本字段)更改大小时,图层不会自动更改大小。
因此,每次文本字段大小发生变化时,您都需要重新绘制底线。
但目前,您正在 viewDidLoad
中配置“底线”层。因此,您将其基于文本字段当时所具有的frame
。但文本字段尚未达到其实际大小。然后它确实改变了大小,同时你的“底线”层就坐在那里——所以现在它的大小是错误的。
一个简单的解决方案是子类化 UITextField 并在每次调用 layoutSubviews
时重新绘制线条:
class MyTextField : UITextField {
var lineLayer : CALayer?
override func layoutSubviews() {
super.layoutSubviews()
self.lineLayer?.removeFromSuperlayer()
let bottomLine = CALayer()
bottomLine.frame = CGRect(x: 0, y: self.bounds.height-7, width: self.bounds.width, height: 1)
bottomLine.backgroundColor = UIColor.black.cgColor
self.layer.addSublayer(bottomLine)
self.lineLayer = bottomLine
}
}
如果您的文本字段是 MyTextField,它将完全按照您的意愿运行。
关于iOS-UITextField : extend the bottom line for ANY resolution,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42888437/