UIVisualEffectView не работает

Я пытаюсь добавить эффект размытия к своему виду, используя следующий код:

let visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .Light)) as UIVisualEffectView
    visualEffectView.frame = containerView.bounds
    containerView.addSubview(visualEffectView)
    containerView.userInteractionEnabled = true
    containerView.bringSubviewToFront(visualEffectView)
    visualEffectView.alpha = 1.0

Однако я не вижу изменений.

ОБНОВИТЬ

Приношу свои извинения, но я не думаю, что ясно изложил свои намерения в исходном вопросе. Я хочу добиться примерно этого:

В моем представлении есть UIImageView, который заполняет весь экран. Затем в нижней части экрана у меня есть контейнер, который представляет собой UIView, который содержит некоторые кнопки и т. Д. Я хочу добавить эффект размытия к containerView, чтобы UIImageView позади него был размытым, где containerView является . Итак, в основном я установил альфа-канал для containerView равным 0,5, что означает его полупрозрачность, и я могу видеть изображение за ним. Сейчас я хочу, чтобы это изображение за контейнером было размыто.

введите здесь описание изображения

ТЕКУЩИЙ ЭФФЕКТ:

введите здесь описание изображения

КОД:

extension UIButton{

func setImage(image: UIImage?, inFrame frame: CGRect?, forState state: UIControlState){
    self.setImage(image, forState: state)

    if let frame = frame{
        self.imageEdgeInsets = UIEdgeInsets(
            top: frame.minY - self.frame.minY,
            left: frame.minX - self.frame.minX,
            bottom: self.frame.maxY - frame.maxY,
            right: self.frame.maxX - frame.maxX
        )
    }
}

}



class SingleImageFeedView: UIViewController {

lazy var mainImageView : UIImageView = {
    let imageView = UIImageView()
    imageView.frame = CGRectMake(0, 0, self.view.frame.width, self.view.frame.width * 1.3)
    imageView.contentMode = UIViewContentMode.ScaleAspectFill
    imageView.backgroundColor = UIColor.clearColor()
    imageView.image = UIImage(named: "pizza")
    return imageView
}()

let containerView : UIView = {
    let this = UIView(frame: CGRectMake(0,0, 600,150))
    this.backgroundColor = UIColor.clearColor()
    this.layer.cornerRadius = 5
    this.layer.borderColor = UIColor(red: (69/255.0), green: (209/255.0), blue: (153/255.0), alpha: 1.0).CGColor
    this.layer.borderWidth = 0.5
    return this
}()


let captionAndProfileImageContainerView : UIView = {
    let this = UIView()
    //this.backgroundColor = UIColor(red: (69/255.0), green: (209/255.0), blue: (153/255.0), alpha: 0.0)
    this.backgroundColor = UIColor.clearColor()
    return this
}()

let profilePicImageView : UIImageView = {
    let imageView = UIImageView()
    imageView.frame = CGRectMake(0, 0, 53, 53)
    imageView.backgroundColor = UIColor.clearColor()
    imageView.image = UIImage(named: "pizza")
    imageView.contentMode = UIViewContentMode.ScaleToFill
    return imageView
}()

let captionTextView: UITextView = {
    let textField = UITextView(frame: CGRectMake(0,0, 150, 100))
    textField.textColor = UIColor.whiteColor()
    textField.editable = false
    textField.text = "dwwdwwwwdwddwd"
    textField.backgroundColor = UIColor.clearColor()
    textField.font = UIFont.systemFontOfSize(12.0)
    return textField
}()

let dividerLineView: UIView = {
    let view = UIView()
    view.backgroundColor = UIColor(white: 0.5, alpha: 0.5)
    return view
}()

let commentAndLikesContainerView : UIView = {
   let view = UIView()
    //view.backgroundColor = UIColor(red: (69/255.0), green: (209/255.0), blue: (153/255.0), alpha: 0.0)
    view.backgroundColor = UIColor.clearColor()
    return view
}()

let commentLabel : UILabel = {
    let label = UILabel()
    label.text = "23"
    return label
}()

let likesLabel : UILabel = {
    let label = UILabel()
    label.text = "25"
    return label
}()

let voteUpButton : UIButton = {
    let button = UIButton(frame: CGRectMake(0,0,25,25))
    button.setImage((scaleImage((UIImage(named: "upvote"))!, toSize: CGSizeMake(25, 25))), inFrame: CGRectMake(0,0,25,25), forState: .Normal)
    button.imageView?.contentMode = UIViewContentMode.Center
    button.imageView?.clipsToBounds = true
    button.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10)
    return button
}()

let voteDownButton : UIButton = {
    let button = UIButton(frame: CGRectMake(0,0,25,25))
    button.setImage((scaleImage((UIImage(named: "upvote"))!, toSize: CGSizeMake(25, 25))), inFrame: CGRectMake(0,0,25,25), forState: .Normal)
    button.imageView?.transform = CGAffineTransformMakeRotation((180.0 * CGFloat(M_PI)) / 180.0)
    button.imageView?.contentMode = UIViewContentMode.Center
    button.imageEdgeInsets = UIEdgeInsetsMake(6, 10, 10, 10)
    button.imageView?.clipsToBounds = true
    return button
}()


let commentButton : UIButton = {
    let button = UIButton(frame: CGRectMake(0,0,25,25))
    button.setImage((scaleImage((UIImage(named: "comment_feed_icon"))!, toSize: CGSizeMake(25, 25))), inFrame: CGRectMake(0,0,25,25), forState: .Normal)
    button.imageView?.contentMode = UIViewContentMode.ScaleAspectFit
    button.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10)
    button.imageView?.clipsToBounds = true
    return button
}()

override func viewDidLoad() {
    super.viewDidLoad()
    self.view.backgroundColor = UIColor.clearColor()
    setupViews()
}

func setupViews() {
    self.captionAndProfileImageContainerView.addSubview(profilePicImageView)
    self.captionAndProfileImageContainerView.addSubview(captionTextView)

    self.commentAndLikesContainerView.addSubview(voteUpButton)
    self.commentAndLikesContainerView.addSubview(voteDownButton)
    self.commentAndLikesContainerView.addSubview(commentButton)
    self.commentAndLikesContainerView.addSubview(commentLabel)
    self.commentAndLikesContainerView.addSubview(likesLabel)

    self.containerView.addSubview(captionAndProfileImageContainerView)
    self.containerView.addSubview(dividerLineView)
    self.containerView.addSubview(commentAndLikesContainerView)




    self.view.addSubview(containerView)
    self.view.bringSubviewToFront(containerView)
    self.view.addSubview(mainImageView)
    self.containerView.bringSubviewToFront(captionAndProfileImageContainerView)
    self.containerView.bringSubviewToFront(dividerLineView)
    self.containerView.bringSubviewToFront(commentAndLikesContainerView)


    profilePicImageView.translatesAutoresizingMaskIntoConstraints = false
    captionTextView.translatesAutoresizingMaskIntoConstraints = false
    voteDownButton.translatesAutoresizingMaskIntoConstraints = false
    containerView.translatesAutoresizingMaskIntoConstraints = false
    voteUpButton.translatesAutoresizingMaskIntoConstraints = false
    commentLabel.translatesAutoresizingMaskIntoConstraints = false
    commentButton.translatesAutoresizingMaskIntoConstraints = false
    commentAndLikesContainerView.translatesAutoresizingMaskIntoConstraints = false
    captionAndProfileImageContainerView.translatesAutoresizingMaskIntoConstraints = false
    likesLabel.translatesAutoresizingMaskIntoConstraints = false
    dividerLineView.translatesAutoresizingMaskIntoConstraints = false
    mainImageView.translatesAutoresizingMaskIntoConstraints = false


    //main imageview constraints
    self.view.addConstraint(NSLayoutConstraint(item: mainImageView, attribute: .Top, relatedBy: .Equal, toItem: self.view, attribute: .Top, multiplier: 1, constant: 35))
    self.view.addConstraint(NSLayoutConstraint(item: mainImageView, attribute: .Leading, relatedBy: .Equal, toItem: self.view, attribute: .Leading, multiplier: 1, constant: 0))
    self.view.addConstraint(NSLayoutConstraint(item: mainImageView, attribute: .Trailing, relatedBy: .Equal, toItem: self.view, attribute: .Trailing, multiplier: 1, constant: 0))
    self.view.addConstraint(NSLayoutConstraint(item: mainImageView, attribute: .CenterX, relatedBy: .Equal, toItem: self.view, attribute: .CenterX, multiplier: 1, constant: 0))
    self.view.addConstraint(NSLayoutConstraint(item: mainImageView, attribute: .Bottom, relatedBy: .Equal, toItem: self.view, attribute: .Bottom, multiplier: 1, constant: 0))
    self.view.sendSubviewToBack(mainImageView)


    //containerview constraints

    self.view.addConstraint(NSLayoutConstraint(item: containerView, attribute: .Bottom, relatedBy: .Equal, toItem: self.view, attribute: .Bottom, multiplier: 1, constant: -10))
    self.view.addConstraint(NSLayoutConstraint(item: containerView, attribute: .Leading, relatedBy: .Equal, toItem: self.view, attribute: .Leading, multiplier: 1, constant: 10))
    self.view.addConstraint(NSLayoutConstraint(item: containerView, attribute: .Trailing, relatedBy: .Equal, toItem: self.view, attribute: .Trailing, multiplier: 1, constant: -10))
    self.view.addConstraint(NSLayoutConstraint(item: containerView, attribute: .Top, relatedBy: .Equal, toItem: self.view, attribute: .Bottom, multiplier: 1, constant: -160))

    //caption and profilepic constraints

    self.view.addConstraint(NSLayoutConstraint(item: captionAndProfileImageContainerView, attribute: .Top, relatedBy: .Equal, toItem: containerView, attribute: .Top, multiplier: 1, constant: 0))
    self.view.addConstraint(NSLayoutConstraint(item: captionAndProfileImageContainerView, attribute: .Leading, relatedBy: .Equal, toItem: containerView, attribute: .Leading, multiplier: 1, constant: 0))
    self.view.addConstraint(NSLayoutConstraint(item: captionAndProfileImageContainerView, attribute: .Trailing, relatedBy: .Equal, toItem: containerView, attribute: .Trailing, multiplier: 1, constant: 0))
    self.view.addConstraint(NSLayoutConstraint(item: captionAndProfileImageContainerView, attribute: .Bottom, relatedBy: .Equal, toItem: containerView, attribute: .Bottom, multiplier: 1, constant: -50))

    self.view.addConstraintsWithFormat("H:|-8-[v0(50)]", views: profilePicImageView)
    self.view.addConstraintsWithFormat("V:|-35-[v0(50)]", views: profilePicImageView)
    profilePicImageView.layer.cornerRadius = 25
    profilePicImageView.layer.masksToBounds = true



    self.view.addConstraint(NSLayoutConstraint(item: captionTextView, attribute: .Top, relatedBy: .Equal, toItem: captionAndProfileImageContainerView, attribute: .Top, multiplier: 1, constant: 0))
    self.view.addConstraint(NSLayoutConstraint(item: captionTextView, attribute: .Leading, relatedBy: .Equal, toItem: profilePicImageView, attribute: .Trailing, multiplier: 1, constant: 10))
    self.view.addConstraint(NSLayoutConstraint(item: captionTextView, attribute: .Trailing, relatedBy: .Equal, toItem: captionAndProfileImageContainerView, attribute: .Trailing, multiplier: 1, constant: 0))
    self.view.addConstraint(NSLayoutConstraint(item: captionTextView, attribute: .Bottom, relatedBy: .Equal, toItem: captionAndProfileImageContainerView, attribute: .Bottom, multiplier: 1, constant: 0))

    //likes and comments and divider


    self.view.addConstraint(NSLayoutConstraint(item: commentAndLikesContainerView, attribute: .Top, relatedBy: .Equal, toItem: captionAndProfileImageContainerView, attribute: .Bottom, multiplier: 1, constant: 0))
    self.view.addConstraint(NSLayoutConstraint(item: commentAndLikesContainerView, attribute: .Leading, relatedBy: .Equal, toItem: containerView, attribute: .Leading, multiplier: 1, constant: 0))
    self.view.addConstraint(NSLayoutConstraint(item: commentAndLikesContainerView, attribute: .Trailing, relatedBy: .Equal, toItem: containerView, attribute: .Trailing, multiplier: 1, constant: 0))
    self.view.addConstraint(NSLayoutConstraint(item: commentAndLikesContainerView, attribute: .Bottom, relatedBy: .Equal, toItem: containerView, attribute: .Bottom, multiplier: 1, constant: 0))


    self.view.addConstraint(NSLayoutConstraint(item: voteUpButton, attribute: .Top, relatedBy: .Equal, toItem: commentAndLikesContainerView, attribute: .Top, multiplier: 1, constant: 0))
    self.view.addConstraint(NSLayoutConstraint(item: voteUpButton, attribute: .Leading, relatedBy: .Equal, toItem: commentAndLikesContainerView, attribute: .Leading, multiplier: 1, constant: 10))


    self.view.addConstraint(NSLayoutConstraint(item: likesLabel, attribute: .Top, relatedBy: .Equal, toItem: commentAndLikesContainerView, attribute: .Top, multiplier: 1, constant: 10))
    self.view.addConstraint(NSLayoutConstraint(item: likesLabel, attribute: .Leading, relatedBy: .Equal, toItem: voteUpButton, attribute: .Trailing, multiplier: 1, constant: 10))

    self.view.addConstraint(NSLayoutConstraint(item: voteDownButton, attribute: .Top, relatedBy: .Equal, toItem: commentAndLikesContainerView, attribute: .Top, multiplier: 1, constant: 0))
    self.view.addConstraint(NSLayoutConstraint(item: voteDownButton, attribute: .Leading, relatedBy: .Equal, toItem: likesLabel, attribute: .Trailing, multiplier: 1, constant: 10))

    self.view.addConstraint(NSLayoutConstraint(item: commentButton, attribute: .Top, relatedBy: .Equal, toItem: commentAndLikesContainerView, attribute: .Top, multiplier: 1, constant: 0))
    self.view.addConstraint(NSLayoutConstraint(item: commentButton, attribute: .Leading, relatedBy: .Equal, toItem: voteDownButton, attribute: .Trailing, multiplier: 1, constant: 30))

    self.view.addConstraint(NSLayoutConstraint(item: commentLabel, attribute: .Top, relatedBy: .Equal, toItem: commentAndLikesContainerView, attribute: .Top, multiplier: 1, constant: 10))
    self.view.addConstraint(NSLayoutConstraint(item: commentLabel, attribute: .Leading, relatedBy: .Equal, toItem: commentButton, attribute: .Trailing, multiplier: 1, constant: 10))



    if !UIAccessibilityIsReduceTransparencyEnabled() {
        self.containerView.backgroundColor = UIColor.clearColor()

        let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Dark)
        let blurEffectView = UIVisualEffectView(effect: blurEffect)
        //always fill the view
        blurEffectView.frame = containerView.bounds
        blurEffectView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]

        self.containerView.insertSubview(blurEffectView, atIndex: 1) //if you have more UIViews, use an insertSubview API to place it where needed


    }
    else {
        self.view.backgroundColor = UIColor(red: (69/255.0), green: (209/255.0), blue: (153/255.0), alpha: 0.5)
    }



    containerView.clipsToBounds = true

}


}

person Alk    schedule 16.06.2016    source источник
comment
Не относится к теме. Вы можете использовать SnapKit для программного добавления ограничений - это проще; D   -  person Savchenko Dmitry    schedule 16.06.2016


Ответы (2)


Попробуйте этот код, работающий на меня

 if !UIAccessibilityIsReduceTransparencyEnabled() {
         self.view.backgroundColor = UIColor.clearColor()

        let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Dark)
        let blurEffectView = UIVisualEffectView(effect: blurEffect)
        //always fill the view
        blurEffectView.frame = self.view.bounds
        blurEffectView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]

        self.view.insertSubview(blurEffectView, atIndex: 1) //if you have more UIViews, use an insertSubview API to place it where needed


    }
    else {
        self.view.backgroundColor = UIColor.blackColor()
    }
person Prashant Tukadiya    schedule 16.06.2016
comment
Ребята, проверьте мою правку, я предоставил дополнительную информацию - person Alk; 16.06.2016

Я сделал простой проект с UIImageView и контейнером. Применение размытия к контейнеру размыло нижнюю фотографию. Для фона контейнеров в раскадровке установлен прозрачный фон.

class ViewController: UIViewController {
override func viewDidLoad() {
    super.viewDidLoad()

    let containerView : UIView = {
        let this = UIView(frame: CGRectMake(100,200, 200,200))
        this.backgroundColor = UIColor.clearColor()
        this.layer.cornerRadius = 5
        this.layer.borderColor = UIColor(red: (69/255.0), green: (209/255.0), blue: (153/255.0), alpha: 1.0).CGColor
        this.layer.borderWidth = 0.5
        return this
    }()

    let visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .Light))

    visualEffectView.frame = containerView.bounds

    self.view.addSubview(containerView)
    containerView.insertSubview(visualEffectView, atIndex: 0)
    let secondImg = UIImageView(image: UIImage(named: "swift_tut.png"))

    secondImg.frame = CGRectMake(150,250, 200,200)

    self.view.addSubview(secondImg)
    self.view.bringSubviewToFront(containerView)





    // Do any additional setup after loading the view, typically from a nib.
}

введите здесь описание изображения

person Haligen    schedule 16.06.2016
comment
Единственное, что containerView - это uiview, а не изображение, не уверен, что это имеет значение. - person Alk; 16.06.2016
comment
Ребята, пожалуйста, проверьте мои изменения, я предоставил дополнительную информацию, если я добавлю это в containerView, все станет серым, я думаю, мне нужно каким-то образом создать другое представление за ним в той же точной позиции и добавить его вместо этого, я не уверен - person Alk; 16.06.2016
comment
Я опубликовал изображение проблемы, с которой я столкнулся на своем устройстве - person Alk; 16.06.2016
comment
Убедитесь, что и ваше представление контейнера, и связанный с ним фон контроллеров представления настроены на очистку. Мне удалось воспроизвести вашу проблему, изменив цвета фона в контейнере или в контроллере представления. - person Haligen; 16.06.2016
comment
Я добавил весь код к вопросу, я установил все возможные цвета фона на clearColor(), которые я смог найти, пожалуйста, посмотрите, может быть, вы найдете что-то, что я пропустил - person Alk; 16.06.2016
comment
Убедитесь, что вы вернули вид контейнера на передний план. Вы добавляете представление контейнера, выводите его на передний план, а затем сразу после этого добавляете представление основного изображения. Кроме того, что вы меня поймали, я использовал ваш код, и он работает. Я обновил свой ответ выше, чтобы отразить мой работающий код. - person Haligen; 16.06.2016
comment
Теперь, подумав об этом, вы также можете проверить фон контроллера представления, связанного с представлением контейнера. Я не видел этого в коде, или, может быть, вы еще не дошли до этого. - person Haligen; 16.06.2016
comment
Он отлично работает на симуляторе iphone6s, однако на моем реальном ipad2 я продолжаю сталкиваться с этой проблемой, может быть проблема с версией ОС, ipad работает под управлением iOS 9.3.2 - person Alk; 16.06.2016
comment
Позвольте нам продолжить это обсуждение в чате. - person Haligen; 16.06.2016
comment
Привет, Канью, пожалуйста, помогите мне с этим stackoverflow.com/questions / 37942009 / - person Diksha; 21.06.2016