【发布时间】:2018-04-17 10:26:37
【问题描述】:
我正在尝试创建一个带有渐变颜色的按钮,但我似乎无法让它工作。我的按钮的borderColor 属性没有应用颜色。我尝试实现another SO post 建议的代码,但它不起作用。不知道为什么。有人可以帮我理解为什么吗?
我用来更改按钮布局的代码是:
// Constraints
myButton.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: 0).isActive = true
myButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -50).isActive = true
myButton.heightAnchor.constraint(equalToConstant: myButton.height).isActive = true
myButton.widthAnchor.constraint(equalToConstant: myButton.width).isActive = true
// Layout
myButton.backgroundColor = UIColor.black
myButton.tintColor = UIColor.white
myButton.layer.cornerRadius = callButtonHeightAndWidth.height / 2
myButton.layer.borderWidth = 10
myButton.setTitle("Test", for: .normal)
myButton.titleLabel?.font = UIFont(name: "HelveticaNeue-Regular", size: 27)
我尝试使用我称为setGradientBorderWidthColor 的函数扩展 UIView,代码如下所示:
func setGradientBorderWidthColor(button: UIButton)
{
let gradientColor = CAGradientLayer()
gradientColor.frame = CGRect(origin: CGPoint.zero, size: button.frame.size)
gradientColor.colors = [UIColor.red.cgColor, UIColor.blue.cgColor, UIColor.green.cgColor]
let shape = CAShapeLayer()
shape.lineWidth = 3
shape.path = UIBezierPath(rect: button.bounds).cgPath
shape.strokeColor = UIColor.black.cgColor
shape.fillColor = UIColor.clear.cgColor
gradientColor.mask = shape
button.layer.addSublayer(gradientColor)
}
我还尝试将上面相同的代码放在我的 ViewController 中的 viewDidLoadfunction 中,但这也不起作用。有什么建议吗?
编辑 1:
使用代码和提供的建议我最终得到了这个。问题是,每当我向按钮添加角半径时,边缘都会被切断。
【问题讨论】:
-
您可以删除 myButton 的高度和宽度锚点。
-
这有什么帮助?
-
没有工作意味着你得到了错误的输出或什么?请试着解释一下。
-
@ViniApp 根本没有输出。运行代码时没有任何反应。
-
我的意思是高度和宽度锚点没有附加值,您可以将其从代码中删除。这确实是一个离题的评论:)
标签: swift