swift 将渐变添加到自定义单元格背景快捷键时出现问题

wtlkbnrh  于 2022-12-22  发布在  Swift
关注(0)|答案(1)|浏览(129)

我已经创建了一个自定义类来应用不同的渐变,正如你所看到的。但是我的问题是,我不能用它来添加渐变到一个自定义单元格

import UIKit

extension UIView {
    // MARK: - Creamos funcion para poder aplicar degrado vertical 2 colores
    func aplicarFondoDegradado() {
        let colorArriba =  UIColor(red: 255/255, green: 4/255, blue: 14/255, alpha: 1.0).cgColor
        let colorAbajo = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 1.0).cgColor
        
        let gradientLayer = CAGradientLayer()
        gradientLayer.colors = [colorArriba, colorAbajo]
        gradientLayer.locations = [0.0, 1.0]
        gradientLayer.frame = self.bounds
                
        self.layer.insertSublayer(gradientLayer, at:0)
    }
    func aplicarDegradadoCultural() {
        let colorInicio =  UIColor(red: 0/255, green: 56/255, blue: 255/255, alpha: 1.0).cgColor
        let colorFin = UIColor(red: 125/255, green: 195/255, blue: 226/255, alpha: 1.0).cgColor
        let gradientLayer = CAGradientLayer()
        gradientLayer.colors = [colorInicio, colorFin]
        gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
        // Set end point.
        gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)
        gradientLayer.frame = self.bounds
        
        self.layer.insertSublayer(gradientLayer, at:0)
    }
    func aplicarDegradadoDeportes() {
        let colorInicio =  UIColor(red: 0/255, green: 56/255, blue: 255/255, alpha: 1.0).cgColor
        let colorFin = UIColor(red: 125/255, green: 195/255, blue: 226/255, alpha: 1.0).cgColor
     let gradientLayer = CAGradientLayer()
        gradientLayer.colors = [colorInicio, colorFin]
        gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
    
        gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)
        gradientLayer.frame = self.bounds
        
        self.layer.insertSublayer(gradientLayer, at:0)
    }
}

它是有效的,但问题是当我试图把梯度应用到动态单元时,它没有显示出来。
这是我的tableview控制器代码,其中包括自定义单元格控制器:

import UIKit

class EventosCustomCellController: UITableViewCell {
    

    @IBOutlet weak var imEvento: UIImageView!
    
    @IBOutlet weak var txtNombreEvento: UILabel!
    
    @IBOutlet weak var txtFechaEvento: UILabel!
    
    @IBOutlet weak var txtEstadoEvento: UILabel!
}

class ListaEventosTableViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "Eventos"
        
        
    }

    // MARK: - Table view data source

    override func viewWillAppear(_ animated: Bool) {
        
        
    }
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return eventos.contarEventos()
    }

    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "prototipoCeldaEvento", for: indexPath) as! EventosCustomCellController
        
        let evento = eventos.buscarEventoPorID(id: indexPath.row)
        cell.layer.borderWidth = 1
        cell.layer.borderColor =  UIColor.black.cgColor
        cell.imageView?.layer.cornerRadius = 30
        
        cell.txtNombreEvento?.text = evento?.nombre
        cell.txtFechaEvento?.text = evento?.fecha
        cell.txtEstadoEvento?.text = evento?.tipo
        //THE PROBLEM IS HERE THE GRADIENT IS NOT SHOWN
        //THE PROBLEM IS HERE THE GRADIENT IS NOT SHOWN
        if evento?.tipo == "deportivo"{
            cell.aplicarDegradadoCultural()}
        else if evento?.tipo == "cultural"{
            cell.aplicarFondoDegradado()            }
        else{
            cell.aplicarDegradadoDeportes()}
        cell.layer.masksToBounds = true
           cell.layer.cornerRadius = 10
        
        cell.imEvento.loadFrom(URLAddress: (evento?.imagenes![0])!)
      
        cell.imEvento.layer.cornerRadius = 25
        cell.imEvento.clipsToBounds = true
        cell.imEvento.layer.borderWidth = 3
        cell.imEvento.layer.borderColor =  UIColor.white.cgColor
        return cell
    }
    

    
    // Override to support conditional editing of the table view.
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
   
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let celdaPulsada = tableView.indexPathForSelectedRow?.row
        eventos.devolverCeldaPulsada (id: celdaPulsada!)
    }}
hfyxw5xn

hfyxw5xn1#

您做错了几件事--而且,您会发现使用自定义“GradientView”要容易得多
单元格被重复使用......使用extension UIView方法,每次使用单元格时,都要插入另一个渐变层。
此外,您不能保证在这一点上有正确的帧。
下面是一个非常简单、基本的自定义“GradientView”:

class GradientView: UIView {
    
    var gradientLayer: CAGradientLayer!
    
    override class var layerClass: AnyClass {
        return CAGradientLayer.self
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        commonInit()
    }
    func commonInit() -> Void {
        gradientLayer = self.layer as? CAGradientLayer
    }
    
}

在Storyboard中,将UIView添加到单元格的Content View中,位于所有标签后面,并将其约束到所有4个边。
然后,将其自定义类指定为GradientView,并将其连接到单元格类,就像标签一样:

@IBOutlet weak var gradientView: GradientView!

然后,删除你的extension UIView并将这些渐变函数移到你的单元格中,看起来像这样:

class EventosCustomCellController: UITableViewCell {
    
    @IBOutlet weak var imEvento: UILabel!
    
    @IBOutlet weak var txtNombreEvento: UILabel!
    
    @IBOutlet weak var txtFechaEvento: UILabel!
    
    @IBOutlet weak var txtEstadoEvento: UILabel!

    @IBOutlet weak var gradientView: GradientView!
    
    func aplicarFondoDegradado() {
        let colorArriba =  UIColor(red: 255/255, green: 4/255, blue: 14/255, alpha: 1.0).cgColor
        let colorAbajo = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 1.0).cgColor
        
        gradientView.gradientLayer.colors = [colorArriba, colorAbajo]
        gradientView.gradientLayer.locations = [0.0, 1.0]

        // start/end points
        gradientView.gradientLayer.startPoint = CGPoint(x: 0.5, y: 0.0)
        gradientView.gradientLayer.endPoint = CGPoint(x: 0.5, y: 1.0)
    }
    func aplicarDegradadoCultural() {
        let colorInicio =  UIColor(red: 0/255, green: 56/255, blue: 255/255, alpha: 1.0).cgColor
        let colorFin = UIColor(red: 125/255, green: 195/255, blue: 226/255, alpha: 1.0).cgColor
        
        gradientView.gradientLayer.colors = [colorInicio, colorFin]

        // start/end points
        gradientView.gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
        gradientView.gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)
    }
    func aplicarDegradadoDeportes() {
        let colorInicio =  UIColor(red: 0/255, green: 56/255, blue: 255/255, alpha: 1.0).cgColor
        let colorFin = UIColor(red: 125/255, green: 195/255, blue: 226/255, alpha: 1.0).cgColor

        gradientView.gradientLayer.colors = [colorInicio, colorFin]

        // start/end points
        gradientView.gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
        gradientView.gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)
    }
    
}

现在您可以将其保存在cellForRowAt中:

if evento?.tipo == "deportivo" {
        cell.aplicarDegradadoCultural()
    }
    else if evento?.tipo == "cultural" {
        cell.aplicarFondoDegradado()
    }
    else {
        cell.aplicarDegradadoDeportes()
    }

单元格的将自动设置渐变属性和大小。

相关问题