以下是用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 类

原文地址: https://www.cveoy.top/t/topic/bEO2 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录