首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >向按钮添加UIVisualEffectView

向按钮添加UIVisualEffectView
EN

Stack Overflow用户
提问于 2016-02-23 13:10:06
回答 1查看 2.5K关注 0票数 1

我有一个透明的删除UIButton添加到一个故事板场景,其中有一个图片作为背景,我增加了一些自动布局的限制。

我希望按钮背景是一个UIVisualEffectView,所以我想通过编程将视图添加到按钮所在的位置,然后删除按钮并将其添加回UIVisualEffectView之上。问题1)这是个好主意吗?还是我应该在视图层次结构中找到位置,并将其放在按钮前一个级别?

这是我到目前为止所拥有的。对于UIButton

代码语言:javascript
复制
@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来说

代码语言:javascript
复制
override func viewDidLoad() {
    super.viewDidLoad()

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

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

提前感谢您的帮助。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-02-23 13:39:17

这里有一个简单的例子,您可以使用它来插入具有振动效应的UIVisualEffectView。

代码语言:javascript
复制
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效果的容器视图。
  • 将容器视图添加到按钮中。
  • 创建一个具有相同效果的振动视图,并将其添加到上面的contentView中。
  • 将标签从按钮移动到振动视图的标题

这是最后的结果。titleLabel文本与振动和应用效果很好地融合在一起。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35578490

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档