我决定学习在没有情节提要的情况下使用Swift。在进行切换之前,我在名为Utilities.swift
的文件中具有一个函数,该函数具有用于设置文本字段样式的功能,当我使用情节提要时,该函数可以正常工作。
class Utilities {
static func styleTextField(_ textfield:UITextField) {
let bottomLine = CALayer()
bottomLine.frame = CGRect(x: 0, y: textfield.frame.height - 2, width: textfield.frame.width, height: 2)
bottomLine.backgroundColor = UIColor.init(red: 48/255, green: 173/255, blue: 99/255, alpha: 1).cgColor
textfield.borderStyle = .none
textfield.layer.addSublayer(bottomLine)
}
}
然后在我的视图控制器中,我有let firstName = UITextField()
,然后有一个Utilities.styleTextField(firstName)
的函数,当我安装情节提要时,该函数可以正常工作。在删除情节提要板并以编程方式添加了约束之后,我可以看到文本字段,但是它是默认的,没有样式。
我的猜测是,到目前为止,您尚未设置文本字段的框架,因此CALayer
未被绘制,因为其大小为(width: 0, height: 0)
。
当您从IB获得组件时,它带有框架,这是您在工具中设置的框架。
在调用函数之前尝试设置框架。