我在一个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传递?。
答案 0 :(得分: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)