首页 > 解决方案 > 当我使用“等宽”约束时如何获取 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 的宽度?

标签: iosswiftswift4

解决方案


一个更好的方法是

  • 子类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

推荐阅读