以下是用 Swift 编写的无需 Nib 的 UICollectionViewCell 类示例代码:

import UIKit

class MyCollectionViewCell: UICollectionViewCell {
    
    let titleLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 16)
        label.textColor = UIColor.black
        label.textAlignment = .center
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupViews()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupViews() {
        backgroundColor = UIColor.white
        layer.cornerRadius = 5
        
        addSubview(titleLabel)
        
        titleLabel.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
        titleLabel.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
        titleLabel.widthAnchor.constraint(equalTo: widthAnchor, constant: -20).isActive = true
        titleLabel.heightAnchor.constraint(equalTo: heightAnchor, constant: -20).isActive = true
    }
    
    func configure(withTitle title: String) {
        titleLabel.text = title
    }
    
}

这个类包含一个标题标签和一个用于设置标题的 configure 方法。在 init 方法中,我们调用 setupViews 方法来设置单元格的外观和布局。其中,我们使用了纯代码来创建和布局标题标签。在 configure 方法中,我们只需将传入的标题文本分配给标题标签即可。

Swift 无需 Nib 创建 UICollectionViewCell 完整教程