在集合视图Swift 5中设置图像和名称,可以通过以下步骤实现:
以下是一个示例代码:
import UIKit
class MyCollectionViewCell: UICollectionViewCell {
let imageView = UIImageView()
let nameLabel = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
// 设置图像视图
imageView.contentMode = .scaleAspectFit
imageView.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(imageView)
// 设置名称标签
nameLabel.textAlignment = .center
nameLabel.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(nameLabel)
// 添加约束
NSLayoutConstraint.activate([
imageView.topAnchor.constraint(equalTo: contentView.topAnchor),
imageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
imageView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
imageView.heightAnchor.constraint(equalTo: contentView.heightAnchor, multiplier: 0.8),
nameLabel.topAnchor.constraint(equalTo: imageView.bottomAnchor),
nameLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
nameLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
nameLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor)
])
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
let data = [
["name": "图像1", "image": "image1"],
["name": "图像2", "image": "image2"],
["name": "图像3", "image": "image3"]
]
override func viewDidLoad() {
super.viewDidLoad()
// 设置集合视图
collectionView.backgroundColor = .white
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(MyCollectionViewCell.self, forCellWithReuseIdentifier: "Cell")
view.addSubview(collectionView)
// 添加约束
NSLayoutConstraint.activate([
collectionView.topAnchor.constraint(equalTo: view.topAnchor),
collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
collectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
}
// MARK: - UICollectionViewDataSource
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return data.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! MyCollectionViewCell
let item = data[indexPath.item]
cell.imageView.image = UIImage(named: item["image"]!)
cell.nameLabel.text = item["name"]
return cell
}
// MARK: - UICollectionViewDelegate
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// 处理选中事件
}
}
在这个示例中,我们创建了一个集合视图,并使用自定义的集合视图单元格来显示图像和名称。数据源方法根据data数组中的数据来设置图像和名称。你可以根据实际需求修改数据源和单元格样式。
领取专属 10元无门槛券
手把手带您无忧上云