繁体   English   中英

在集合单元格中添加背景视图

[英]Add background view in collection cell

我使用 UITableViewCell.xib 来自定义单元格。 我显示文本和图片,视图添加到单元格的背景。 只有 7 个单元格,在一个单元格中,我需要用另一个 UIView.xib 替换此背景。 我试图实现这一点,但它没有给我结果,所有单元格的背景都是相同的。 或者如何将背景视图单元格的属性更改为我的 View.xib

CollectionCell.swift

import UIKit

class CollectionViewCell: UICollectionViewCell {

    static var identifier: String = "CollectionViewCell"

    @IBOutlet weak var icon: UIImageView!
    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var customBackgoundView: UIView!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code

    }
}

客户视图.swift

import UIKit

class CustomBackgroundView: UIView {

    @IBOutlet weak var contentView:UIView!


    //MARK: Override
    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }

    private func commonInit() {
        Bundle.main.loadNibNamed("CustomBackgroundView", owner: self, options: nil)
        addSubview(contentView)
        contentView.frame = self.bounds
    }
}

CollectionView.swift让背景 = CustomBackgroundView()

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CollectionViewCell.identifier, for: indexPath) as? CollectionViewCell


            // here i'm doing something wrong because nothing changes
  if indexPath.row == 3 {
        cell?.customBackgoundView = background
        cell?.contentView.addSubview(background)
    }
        return cell ?? UICollectionViewCell()
    }

您需要在 indexPath.row == 3 上加载 UIView ,如下所示

let myView = Bundle.main.loadNibNamed("yourXibView", owner: nil, options: nil)![0] as! UIView

然后添加您的收藏视图的背景主视图

问题是当你想在单元格上添加一些东西时,它应该添加它的内容视图。 所以,尝试与 contentView 一起使用

  func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CollectionViewCell.identifier, for: indexPath) as? CollectionViewCell
 if indexPath.row == 3 {
                 var backgroundView = Bundle.main.loadNibNamed("CustomBackgroundView", owner: self, options: nil)![0] as! UIView
             backgroundView.frame = cell.contentView.frame
            cell.contentView.addSubview(yourCustomView)
            cell.contentView.sendSubviewToBack(yourCustomView)
        return cell!
                } else {
                    return cell ?? UICollectionViewCell()
                }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM