模糊效果未出现在 UITableViewCell 中

Blur effect not appearing in UITableViewCell

我正在尝试为我的视图添加模糊效果。我创建了这样的模糊效果

let blurLabel: UIVisualEffectView = {
    let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.dark)
    let blurEffectView = UIVisualEffectView(effect: blurEffect)


    return blurEffectView
    }()

然后我像这样将它添加到子视图中,并用它设置约束

 override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)
        let view = tableViewCell

        addSubview(view)
        view.addSubview(blurLabel)

 blurLabel.leftAnchor.constraint(equalTo: self.leftAnchor,constant:0).isActive = true
        //blurLabel.topAnchor.constraint(equalTo: self.topAnchor, constant: 178).isActive = true
        blurLabel.widthAnchor.constraint(equalToConstant: 375).isActive = true
        blurLabel.heightAnchor.constraint(equalToConstant: 180).isActive = true

但是当我运行应用程序时它根本没有出现

编辑:正如@HAS 和@Fogmeister 所建议的,您也可以使用translatesAutoResizingMaskIntoConstraints = false,因为它是在不指定显式框架的情况下使用自动布局的更好解决方案。

您必须像这样将 frame 分配给 UIVisualEffectView

 let blurLabel: UIVisualEffectView = {
    let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.dark)
    let blurEffectView = UIVisualEffectView(effect: blurEffect)
    blurEffectView.frame = CGRect(x: 0, y: 0, width: 60, height: 40) //give desirable frame
    return blurEffectView
 }()

如果您愿意,除了提供显式框架之外,您还可以将 blurView 提供给您的任何视图或子视图。

let blurLabel: UIVisualEffectView = {
    let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.dark)
    let blurEffectView = UIVisualEffectView(effect: blurEffect)    
    blurEffectView.frame = myMainview.bounds //Blur effect's frame
    return blurEffectView
}()

override func viewDidLoad() {
    super.viewDidLoad()
    // Use it somewhere using
    self.view.insertSubview(blurEffectView, belowSubview: myAnotherView)
    // You may also use any of the subviews too, instead of the self.view
    /// self.myView.insertSubview(blurEffectView, belowSubview: myAnotherView)
}

要解决此问题,您只需停止它自动创建约束即可。像这样...

let blurLabel: UIVisualEffectView = {
    let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.dark)
    let blurEffectView = UIVisualEffectView(effect: blurEffect)
    // this line will stop constraints being added for a zero frame
    blurEffectView.translatesAutoResizingMaskIntoConstraints = false
    return blurEffectView
}()