ios - 当我使用“等宽”约束时如何获取 UIView 的宽度或高度
问题描述
我需要帮助来解决这个问题:我有一个 UITextFiled 并且我正在尝试使用以下代码在底部应用一个边框:
func addBottomBorderWithColor(color: UIColor, width: CGFloat) {
let border = CALayer()
border.backgroundColor = color.cgColor
border.frame = CGRect(x: 0, y: self.frame.size.height - width, width: self.frame.size.width, height: width)
self.layer.addSublayer(border)
}
问题是结果不正确,边框超出了文本字段,因为在文本字段中我使用的是“等宽约束”,而设计时的宽度与“Didload()”时的宽度不同。有一种方法可以在“等宽约束”更正后获得 textField 的宽度?
解决方案
一个更好的方法是
- 子类
UITextField
- 在初始化时创建“下划线边框”层
- 更改该图层的框架
layoutSubviews()
例子:
@IBDesignable
class UnderlinedTextField: UITextField {
let underlineLayer: CALayer = CALayer()
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
func commonInit() -> Void {
layer.addSublayer(underlineLayer)
underlineLayer.backgroundColor = UIColor.black.cgColor
}
override func layoutSubviews() {
super.layoutSubviews()
underlineLayer.frame = CGRect(x: 0, y: bounds.height - 2.0, width: bounds.width, height: 2)
}
}
结果(我给文本字段设置了背景颜色,.cyan
以便于查看):
当字段大小发生变化时,它会自动调整“下划线”的大小 - 例如在设备旋转时:
请注意,通过制作它@IBDesignable
,您还可以在设计时看到下划线层。
此示例使用默认黑色作为“下划线”,但您可以通过代码更改它,就像任何其他属性更改一样,例如:
testField.underlineLayer.backgroundColor = UIColor.red.cgColor
推荐阅读
- python - 如何在指定的时间段内调用该函数?
- ruby-on-rails - Session[:user_return_to] 在登录后重定向回当前页面时为零
- sql - PHPMyAdmin 匹配具有两个或多个字符串的行
- java - 删除 .m2 文件夹后 Maven 安装错误
- security - 如何保护 JCL FTP 中的存储密码?
- tsql - 计算多行的 Zscore
- javascript - 如何使用类列表添加和删除活动视图类型?
- javascript - 在特定位置替换字符串中的单词
- python - 删除所有列值也是 NA 的 NA 行
- php - 在 localhost 中重写 URL 不起作用