ios - 在按钮周围添加 CAShapeLayer

标签 ios swift

我创建了一个圆形的 CAShapeLayer,我想将它添加到 View 中的按钮周围。由于动画目的,我这样做而不是边框​​。我不想要按钮周围的边框,我宁愿有一个形状。这就是我添加它的方式,但出于某种原因,它没有直接在按钮周围添加形状。

这是我添加图层的代码

recordLine = CAShapeLayer()
let circularPath = UIBezierPath(arcCenter: recordButton.center, radius: recordButton.frame.width / 2, startAngle: 0, endAngle: 2 * CGFloat.pi, clockwise: true)
recordLine.path = circularPath.cgPath
recordLine.strokeColor = UIColor.white.cgColor
recordLine.fillColor = UIColor.clear.cgColor
recordLine.lineWidth = 5
view.layer.addSublayer(recordLine)

这就是它出于某种原因添加行的方式。 Actual position of the layer

最佳答案

发生这种情况是因为您在正确渲染自动布局约束之前添加了形状层。

请在添加形状层之前添加一行:self.view.layoutIfNeeded()

 @IBOutlet weak var roundButton: UIButton!
    override func viewDidLoad() {
        super.viewDidLoad()
        roundButton.layer.cornerRadius = 50.0
        roundButton.clipsToBounds = true
        roundButton.alpha = 0.5
        self.view.layoutIfNeeded()

        let recordLine = CAShapeLayer()
        let circularPath = UIBezierPath(arcCenter: roundButton.center, radius: roundButton.frame.width / 2, startAngle: 0, endAngle: 2 * CGFloat.pi, clockwise: false)
        recordLine.path = circularPath.cgPath
        recordLine.strokeColor = UIColor.black.cgColor
        recordLine.fillColor = UIColor.clear.cgColor
        recordLine.lineWidth = 10
        view.layer.addSublayer(recordLine)

    }

请查看引用图片enter image description here 这对我有用。

关于ios - 在按钮周围添加 CAShapeLayer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47974618/

相关文章:

ios - Swift 和 SecTrust

ios - 无法快速获取我的信息 datatask 3

swift - 在 Swift 中实例化新 Codable 对象的最简单方法是什么?

ios - View 加载时自动异步运行 UITableView 刷新功能

ios - 应用程序无法在 iPhone 6 模拟器上正常运行

ios - 更新 UITabBarController 的所有 View Controller

iphone - 改变 UIButton 状态时内部尺寸不更新

iOS Firebase Stripe Integration with/Cloud Functions,相当于 iOS 中的 push() 和 push Id

ios - Swift 中的 Firebase .childChanged 问题

objective-c - 如何在 xcode 中预览基于自定义代码的 View ?