0

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

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

这是我到目前为止所拥有的。对于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)
}

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

提前感谢您的帮助。

4

1 回答 1

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 效果的容器视图。
  • 将容器视图添加到按钮。
  • 创建一个效果相同的活力视图,并将其添加到上述containerView的contentView中。
  • 将标签从按钮移动到活力视图的标题

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

在此处输入图像描述

于 2016-02-23T13:39:17.000 回答