从已定义的Bezier路径创建UI按钮?

问题描述 投票:-3回答:1

我在一个View Controller中有一系列定义的Bezier路径(默认)。但具体来说,我想让它们中的一个成为UIButton(它不需要在任何地方领先,但如果可以在触摸时打印某些东西会很棒)。

通过查看一些类似的问题,我能够在模拟器上单独定义我想要的Bezier路径和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传递?

ios swift uibutton uibezierpath
1个回答
0
投票

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)
© www.soinside.com 2019 - 2024. All rights reserved.