UIButton 的渐变未显示
Posted
技术标签:
【中文标题】UIButton 的渐变未显示【英文标题】:Gradient of UIButton is not showing 【发布时间】:2019-08-25 00:44:18 【问题描述】:我正在尝试在按钮上添加渐变,但它没有显示出来。所有其他按钮部分都可以正常工作并完美显示!
创建按钮的函数
private func createButtonMenu(buttonTitle: String, buttonIcon: UIImage, colorOne: UIColor, colorTwo: UIColor) -> UIButton
let button = UIButton()
button.setTitle(buttonTitle, for: .normal)
button.translatesAutoresizingMaskIntoConstraints = false
button.contentHorizontalAlignment = .leading
button.contentVerticalAlignment = .bottom
button.contentEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 10, right: 0)
button.layer.cornerRadius = 30
button.layer.masksToBounds = true
let icon = UIImageView(image: buttonIcon)
icon.translatesAutoresizingMaskIntoConstraints = false
button.addSubview(icon)
button.heightAnchor.constraint(equalToConstant: 100).isActive = true
icon.topAnchor.constraint(equalTo: button.topAnchor, constant: 10).isActive = true
icon.leadingAnchor.constraint(equalTo: button.leadingAnchor, constant: 10).isActive = true
let gradientLayer = CAGradientLayer()
gradientLayer.frame = button.bounds
gradientLayer.colors = [UIColor.red, UIColor.blue]
gradientLayer.locations = [0.0, 1.0]
gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)
button.layer.insertSublayer(gradientLayer, at: 0)
//button.backgroundColor = .red
icon.widthAnchor.constraint(equalToConstant: 30).isActive = true
icon.heightAnchor.constraint(equalToConstant: 30).isActive = true
return button
在视图中插入按钮的函数
private func configuringButtons()
//Creating buttons
let userButtonMenu: UIButton = createButtonMenu(buttonTitle: "009", buttonIcon: #imageLiteral(resourceName: "woman"), colorOne: .red, colorTwo: .blue)
view.addSubview(userButtonMenu)
【问题讨论】:
没有工作克里斯,背景颜色按预期工作,但渐变没有 让button.addSubview(icon)
尝试button.imageView = icon
button.layer.insertSublayer(gradientLayer, at: 0) 你不认为它不应该是 0 但最重要的是我的意思是 totallayers.count
【参考方案1】:
渐变层中的颜色必须是 CGColor
类型,而不是 UIColor
。
gradientLayer.colors = [UIColor.red.cgColor, UIColor.blue.cgColor]
【讨论】:
@VinniciusPereira 您是否遇到任何错误或只是无法正常工作?以上是关于UIButton 的渐变未显示的主要内容,如果未能解决你的问题,请参考以下文章
蓝色渐变图像被错误地拉伸为 UIButton 的橙色渐变图像