【问题标题】:Blur cell image on cell button click in UITableView在 UITableView 中单击单元格按钮时模糊单元格图像
【发布时间】:2018-06-20 09:31:47
【问题描述】:

在表格视图单元格中,我有一个图像和一个按钮,现在我想通过单击按钮来模糊图像

我有以下代码:-

func blurEffect(){
    let blur = UIBlurEffect(style: UIBlurEffectStyle.light)
    let blurView = UIVisualEffectView(effect: blur)
    var imageView = UIImageView()
    blurView.frame = imageView.bounds
    view.addSubview(blurView)
}

// I am Calling blur effect on at tick button action as below


@objc func tickButton(btn : UIButton){
    blurEffect() 
}


 //In tableView

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = MealTableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! MealCell

    cell.imgMeal.image = UIImage(named: mealImage[indexPath.row])

    cell.btnTick.addTarget(self, action: #selector(MealPlanViewController.tickButton(btn:)), for: .touchUpInside)
    return cell
}

【问题讨论】:

  • 你应该把这段代码放在你的cell类中。不在ViewController
  • 我想飞!!
  • 请不要问我要,问你的问题

标签: ios swift uitableview uiblureffect


【解决方案1】:

试试这个代码 -

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = MealTableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! MealCell

    cell.imgMeal.image = UIImage(named: mealImage[indexPath.row])
    cell.btnTick.tag = indexPath.row
    cell.btnTick.addTarget(self, action: #selector(MealPlanViewController.tickButton(btn:)), for: .touchUpInside)
    return cell
}

您必须在特定单元格上添加模糊视图,然后单击..... 你可以通过按钮标签在func中获取单元格,比如

 @objc func tickButton(btn : UIButton){
    let index = IndexPath.init(row: btn.tag, section: 0)
    let cell = tbl.cellForRow(at: index) as! newTbl
    let blur = UIBlurEffect(style: UIBlurEffectStyle.light)
    let blurView = UIVisualEffectView(effect: blur)
    blurView.frame = cell.img.bounds
    cell.img.addSubview(blurView)
}

但是每次在 cellForRowAtIndex 方法中重新加载表格时,您必须保存模糊单元格的 indexPath 或行并绘制它。 因为当表格视图重新加载或重用相同的单元格时,它会显示模糊。

【讨论】:

    【解决方案2】:

    更改以下函数(假设它在MealCell 类中)...

    func blurEffect() {
    
      let blur = UIBlurEffect(style: UIBlurEffectStyle.light)
      let blurView = UIVisualEffectView(effect: blur)
    
      blurView.frame = self.imgMeal.bounds
      self.addSubview(blurView)
    }
    

    您可以在 tableview 单元格中创建按钮的 IBAction,即 MealCell 类。

    @IBAction func tickButton(_ sender : UIButton){
        blurEffect() 
    }
    

    【讨论】:

    • 你如何在tableview之外得到cell.imgMeal.bounds
    • 你的答案不正确,需要更多代码输出
    • 很好,谢谢 Kartik...Ans。修改。
    • 一样吗?再次,你如何在按钮操作中调用blurEffect() ,如果你喜欢,它将调用当前类函数而不是单元类\
    • @Anbu.karthik 考虑MealCell 中具有imgMealoutlet 的代码。