【问题标题】:Animate Gradient View Upon Cell Selection单元格选择时动画渐变视图
【发布时间】:2022-01-02 11:12:19
【问题描述】:

我希望为渐变视图实现动画。

有什么步骤可以帮助解决这个问题吗?目前,我已经准备好一切,并且在单元格上附加了一个静态背景,在选择时显示并在不选择时隐藏。最困难的部分是动画工作,我需要一些帮助。

【问题讨论】:

  • "目前我已经准备好了一切" 在哪里?我没有看到一行代码。
  • 一切准备就绪。但您没有共享任何代码。请分享代码

标签: ios swift xcode interface-builder gradient


【解决方案1】:

你可以试试这个方法 ->视图控制器

class VC2: UIViewController {

// MARK:- IBOutlets
@IBOutlet weak var tblSample: UITableView!

// MARK:- Private Variables
private var SelectedCell: Int?

// MARK:- View Lifecycle
override func viewDidLoad() {
    super.viewDidLoad()
    initialConfig()
}

// MARK:- Initial Config
private func initialConfig() {
    tblSample.delegate = self
    tblSample.dataSource = self
    
    } 
}

//表视图委托

extension VC2: UITableViewDelegate {

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 50
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    SelectedCell = indexPath.row
    tblSample.reloadData()
    }
}

// 表数据源

extension VC2: UITableViewDataSource {

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 10
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell()
    cell.textLabel?.text = "\(indexPath.row)"
    cell.selectionStyle = .none
    if SelectedCell == indexPath.row {
        DispatchQueue.main.async {
            UIView.animate(withDuration: 1,delay: 0.5, options: .curveEaseIn) {
                cell.contentView.applyGradient(colours: [.white,.blue])
            }
        }
    }
    return cell
   }
}

// 应用和移除渐变的视图扩展

extension UIView {

@discardableResult
func applyGradient(colours: [UIColor]) -> CAGradientLayer {
    return self.applyGradient(colours: colours, locations: nil)
}

@discardableResult
func applyGradient(colours: [UIColor], locations: [NSNumber]?) -> CAGradientLayer {
    let gradient: CAGradientLayer = CAGradientLayer()
    gradient.frame = self.bounds
    gradient.colors = colours.map { $0.cgColor }
    gradient.locations = locations
    self.layer.insertSublayer(gradient, at: 0)
    return gradient
}

func removeGradient() {
    for lay in self.layer.sublayers ?? [] {
        if lay is CAGradientLayer {
            lay.removeFromSuperlayer()
        }
    }
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-26
    • 1970-01-01
    • 2014-10-22
    • 1970-01-01
    • 2022-10-14
    • 1970-01-01
    • 2020-04-04
    • 1970-01-01
    相关资源
    最近更新 更多