在UITableView中单击单元格按钮上的单元格图像模糊

时间:2018-06-20 09:31:48

标签: ios swift uitableview uiblureffect

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

我有以下代码:-

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
}

2 个答案:

答案 0 :(得分:2)

尝试此代码-

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)
}

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

答案 1 :(得分:-1)

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

func blurEffect() {

  let blur = UIBlurEffect(style: UIBlurEffectStyle.light)
  let blurView = UIVisualEffectView(effect: blur)

  blurView.frame = self.imgMeal.bounds
  self.addSubview(blurView)
}

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

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