首页 > 解决方案 > 从已定义的 Bezier 路径创建 UIbutton?

问题描述

我在一个视图控制器(默认)中有一系列定义的贝塞尔路径。然而,具体来说,我想让其中一个成为 UIButton (它还不必引导到任何地方,但如果它可以在触摸时打印一些东西会很棒)。

通过查看一些类似的问题,我已经能够在模拟器上分别定义我想要的贝塞尔路径和 UIButton,但无法将它们拼接在一起。

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

    let circlePath = UIBezierPath(arcCenter: CGPoint(x: 200, y: 350), radius: CGFloat(150), startAngle: CGFloat(0), endAngle:CGFloat(Double.pi * 2), clockwise: true)

    let shapeLayer = CAShapeLayer()
    shapeLayer.path = circlePath.cgPath

    //change the fill color
    shapeLayer.fillColor = UIColor.clear.cgColor
    //you can change the stroke color
    shapeLayer.strokeColor = UIColor.gray.cgColor
    //you can change the line width
    shapeLayer.lineWidth = 7.5

    view.layer.addSublayer(shapeLayer)

  let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))
        button.backgroundColor = .green
        button.setTitle("Test Button", for: .normal)
        button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)

        self.view.addSubview(button)
    }

    @objc func buttonAction(sender: UIButton!) {
        print("Button tapped")
    }

}

如何将 circlePath 作为 UIButton 传递?

标签: iosswiftuibuttonuibezierpath

解决方案


UIButton 是 UIView,因此您可以将创建的图层添加到按钮,就像您创建视图一样:

button.layer.addSublayer(shapeLayer)

请注意,该层将覆盖 UIButton 的标签,但解决此问题的简单方法是更改​​层的 z 位置:

shapeLayer.zPosition = -1

例如,如果您想为按钮添加圆形图层:

let circlePath = UIBezierPath(ovalIn: button.bounds)
let shapeLayer = CAShapeLayer()
shapeLayer.path = circlePath.cgPath
shapeLayer.zPosition = -1   
button.layer.addSublayer(shapeLayer)

或者,匹配示例中的圆圈,但在形状之前创建按钮:

// define circle parameters
let radius: CGFloat = 150
let center = CGPoint(x: 200, y: 350)

// create the button
let button = UIButton(frame: CGRect(origin: center.applying(CGAffineTransform(translationX: -radius, y: -radius)),
                                        size: CGSize(width: 2 * radius, height: 2 * radius)))

// create the circle layer
let circlePath = UIBezierPath(ovalIn: button.bounds)
let shapeLayer = CAShapeLayer()
shapeLayer.path = circlePath.cgPath
shapeLayer.zPosition = -1

// add the circle layer to the button
button.layer.addSublayer(shapeLayer)

view.addSubview(button)

推荐阅读