【问题标题】:Adding CAShapeLayer to UIButton but it appears under the border line将 CAShapeLayer 添加到 UIButton 但它出现在边框线下方
【发布时间】:2018-01-03 03:17:48
【问题描述】:

我想在 UIButton 的边框上添加一个红点。我当前添加点的代码是这样的:

required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setUp()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setUp()
    }

    override func setUp() {
        super.setUp()
        layer.borderWidth = borderWidth
        layer.borderColor = normalBorderColor.cgColor

        let redDotLayer = CAShapeLayer()
        redDotLayer.path = CGPath(ellipseIn: CGRect(x: 30, y: -3.5, width: 8, height: 8), transform: nil)
        redDotLayer.fillColor = UIColor.red.cgColor
        layer.addSublayer(redDotLayer)
    }

但是,当我添加红点时,它会出现在 边界线的下方。我需要它位于边界线的顶部。

我在这里做错了什么?

【问题讨论】:

    标签: ios uibutton cashapelayer


    【解决方案1】:

    你的方法没有错。

    1. 例如,只需考虑将子视图添加到父视图UIView,子视图始终停留在父视图内部,无法添加到父视图之上。
    2. 同样的场景适用于CALayer。你不能在父层之上addSublayer。
    3. 作为一个例外,

    与视图不同,超级图层不会自动剪切位于其边界矩形之外的子图层的内容。相反,默认情况下,超级图层允许其子图层完整显示。但是,您可以通过将图层的 maskToBounds 属性设置为 YES 来重新启用剪辑。

    根据苹果文档,子层可以超出父可见区域,但不能超出父级。

    1. 即使是以下方法也无济于事。

      - insertSublayer:atIndex:

      - insertSublayer:above:

      - insertSublayer:below:

    • 添加子层: 将图层附加到图层的子图层列表中。

    解决方案

    在按钮周围再画一个CAShapeLayer。

    【讨论】:

      【解决方案2】:

      CALayers 可能最后才在自身周围绘制边框。我认为对您来说最简单的解决方案就是在单独的图层中绘制边框,以便您可以控制排序。

      override func setUp() {
        super.setUp()
      
        let borderLayer = CALayer()
        borderLayer.borderWidth = borderWidth
        borderLayer.borderColor = normalBorderColor.cgColor
        layer.addSublayer(borderLayer)
      
        let redDotLayer = CAShapeLayer()
        redDotLayer.path = CGPath(ellipseIn: CGRect(x: 30, y: -3.5, width: 8, height: 8), transform: nil)
        redDotLayer.fillColor = UIColor.red.cgColor
        layer.addSublayer(redDotLayer)
      }
      

      【讨论】:

        【解决方案3】:

        在我的代码中,我无法使用另一个图层作为边框,因此我使用了另一个UIView 作为边框。 一个重要的部分是将边界 UIView isUserInteractionEnabled 设置为 false,以便响应者链将其传递给 UIButton:

        let borderView = UIView(frame: .zero)
        borderView.backgroundColor = .clear
        borderView.layer.borderWidth = 0.5
        borderView.layer.borderColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.18).cgColor
        borderView.layer.cornerRadius = 19
        // Dont't forget to set it to false or else the button won't work
        borderView.isUserInteractionEnabled = false
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-01-07
          • 2011-05-19
          相关资源
          最近更新 更多