gpt4 book ai didi

ios - 在收集单元格中添加背景 View

转载 作者:行者123 更新时间:2023-12-01 18:03:40 26 4
gpt4 key购买 nike

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

}
}

CustomeView.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()
}

最佳答案

问题是,当您想在单元格上添加某些内容时,应该添加它的contentview。因此,尝试与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()
}

关于ios - 在收集单元格中添加背景 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61344051/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com