gpt4 book ai didi

swift - 将 UIVisualEffectView 添加到按钮

转载 作者:行者123 更新时间:2023-11-30 10:06:38 25 4
gpt4 key购买 nike

我在 Storyboard场景中添加了一个透明的删除UIButton,该场景有一张图片作为背景,并且我为其添加了一些自动布局约束。

我希望按钮背景是 UIVisualEffectView 所以我正在考虑以编程方式将 View 添加到按钮所在的位置,然后删除按钮并将其添加回来,以便它位于 的顶部>UIVisualEffectView问题 1)这是一个好主意 - 还是我应该在 View 层次结构中找到该位置并将其放置在按钮之前的一层?

这是我迄今为止所拥有的。对于UIButton:

@IBOutlet weak var delete: UIButton! {
didSet {
let borderAlpha = CGFloat(0.7)
let cornerRadius = CGFloat(5.0)
delete.setTitle("Delete", forState: UIControlState.Normal)
delete.setTitleColor(UIColor.redColor(), forState: UIControlState.Normal)
delete.backgroundColor = UIColor.clearColor()
delete.layer.borderWidth = 1.0
delete.layer.borderColor = UIColor(white: 1.0, alpha: borderAlpha).CGColor
delete.layer.cornerRadius = cornerRadius
}
}

对于UIVisualEffectView:

override func viewDidLoad() {
super.viewDidLoad()

let visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .Light))
visualEffectView.frame = delete.frame
visualEffectView.bounds = delete.bounds
view.addSubview(visualEffectView)
}

这会产生一个模糊的 View ,其大小与按钮相同,但它不在按钮的顶部。 问题 2)我是否也需要以某种方式传递自动布局约束?

提前感谢您的帮助。

最佳答案

这是一个简单的示例,您可以使用它来插入具有活力效果的 UIVisualEffectView。

let button = UIButton(frame: CGRect(x: 0, y: 0, width: 500, height: 100))
button.setTitle("Visual Effect", forState: .Normal)

let gradientLayer = CAGradientLayer()
gradientLayer.colors = [UIColor.blueColor().CGColor, UIColor.redColor().CGColor, UIColor.brownColor().CGColor, UIColor.greenColor().CGColor, UIColor.magentaColor().CGColor, UIColor.purpleColor().CGColor, UIColor.cyanColor().CGColor]
gradientLayer.locations = [0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1]
button.layer.insertSublayer(gradientLayer, atIndex: 0)
gradientLayer.frame = button.bounds

let containerEffect = UIBlurEffect(style: .Dark)
let containerView = UIVisualEffectView(effect: containerEffect)
containerView.frame = button.bounds

containerView.userInteractionEnabled = false // Edit: so that subview simply passes the event through to the button

button.insertSubview(containerView, belowSubview: button.titleLabel!)
button.titleLabel?.font = UIFont.boldSystemFontOfSize(30)

let vibrancy = UIVibrancyEffect(forBlurEffect: containerEffect)
let vibrancyView = UIVisualEffectView(effect: vibrancy)
vibrancyView.frame = containerView.bounds
containerView.contentView.addSubview(vibrancyView)

vibrancyView.contentView.addSubview(button.titleLabel!)

而且,这就是我所做的,

  • 创建一个按钮。
  • 创建一个渐变图层并将其添加到按钮的 0 索引处。
  • 创建一个具有 UIBlurEffectDark 效果的容器 View 。
  • 将容器 View 添加到按钮。
  • 创建一个效果相同的vibrancy view,并将其添加到上述containerView的contentView中。
  • 将标签从按钮移至活力 View 的标题

而且,这是最终结果。 titleLabel 文本与活力和应用的效果完美地融合在一起。

enter image description here

关于swift - 将 UIVisualEffectView 添加到按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35578490/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com