使用 "Equal width" 约束时如何获取 UIView 的宽度或高度

How to get Width or Height of a UIView when I'm using "Equal width" constrain

我需要帮助来解决这个问题:我有一个 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)
    }

问题是结果不正确,边框超出了文本字段,因为在文本字段中我使用的是 "Equal width constrain" 并且设计时的宽度与 [= 处的宽度不同17=] 时间。 "Equal width constrain" 更正后,有办法获取 textField 的宽度吗?

我自己找到了一个可能的解决方案(不是最完美的)。 因为Constrains可能应用在DidLoad()之后和viewDidLayoutSubviews()之后,所以我在函数viewDidAppear()中调用了添加边框的函数。现在,即使新边框的显示稍有延迟,它也能正常工作。

最好的方法是子class 一个 UITextFiled,如此处所述。

在这种情况下,对象创建正确

覆盖 bounds 变量并调用 didSet 中的边框绘图。每次视图更改边界时,您的图层都会更新。

    var border = CALayer()

    init(frame: CGRect) {
        super.init(farme: frame)

        self.layer.addSublayer(border)
    }

    override var bounds: CGRect {
        didSet {
            addBottomBorderWithColor(color: .black, width: 2)
        }
    }

    func addBottomBorderWithColor(color: UIColor, width: CGFloat) {
        border.backgroundColor = color.cgColor
        border.frame = CGRect(x: 0, y: self.frame.size.height - width, width: self.frame.size.width, height: width)
        self.layer.setNeedsLayout()
    }

更好的方法是

  • 子类UITextField
  • 在初始化时创建 "underline border" 层
  • 更改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 背景色):

它会在字段大小发生变化时自动调整 "underline" 的大小 - 例如在设备旋转时:

请注意,通过将其设置为@IBDesignable,您还可以在设计时看到下划线层。

此示例使用 "underline" 的默认黑色,但您可以通过代码更改它,就像任何其他 属性 更改一样,例如:

testField.underlineLayer.backgroundColor = UIColor.red.cgColor