ios - 从已定义的 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 传递?
解决方案
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)
推荐阅读
- android - 如何检测密钥是否在 TEE 或钛芯片内部生成
- rust - 内置测试器“定义”没有像我预期的那样工作
- haskell - 如何建立对 Servant 类型错误的直觉?
- oracle - 如何使用 Oracle XML DB Webservices 将表作为一行返回
- android - 从服务器获取数据后如何缓存数据?
- c# - 将文件分类到目录中
- r - Shiny 中的 Kmeans 实现
- wordpress - 如何使用 elementor 在 wordpress 中从头开始自定义页眉和页脚?
- android - “getDisplayLanguage()”总是返回“English”
- firebase-dynamic-links - 如何让我的 Firebase 动态链接重定向到我在桌面上的网站和我在移动设备上的即时应用