You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift纯代码实现UICollectionView的UIImageView上方添加居中UILabel

问题解决方案

核心错误原因

  • 子视图添加顺序错误:后添加的UIImageView层级高于先添加的UILabel,直接覆盖了label,导致文字显示在图片下方不可见
  • 布局参数配置错误:当前label的frame没有做居中计算,且imageView写死宽高不符合cell复用逻辑
  • 小瑕疵:configure方法参数名和成员变量label重名,容易引发逻辑错误

完整修改代码

import UIKit

class ExploreCollectionViewCell: UICollectionViewCell {
    static let identifier = "ExploreCollectionViewCell"

    private let label: UILabel = {
        let label = UILabel()
        label.textColor = .white
        label.font = UIFont(name: Settings.shared.MAIN_APP_FONT_BOLD, size: 13)
        // 新增:文字水平居中
        label.textAlignment = .center
        // 可选配置:添加阴影提升浅色背景下的文字辨识度
        label.shadowColor = .darkGray
        label.shadowOffset = CGSize(width: 1, height: 1)
        return label
    }()

    private let imageView: UIImageView = {
        let imageView = UIImageView()
        imageView.clipsToBounds = true
        imageView.layer.cornerRadius = 0
        imageView.contentMode = .scaleAspectFill
        return imageView
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        // 调整添加顺序:先加imageView,再加label,保证label在视图最上层
        contentView.addSubview(imageView)
        contentView.addSubview(label)
    }

    required init?(coder: NSCoder) {
        fatalError()
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        // imageView撑满整个cell内容区域
        imageView.frame = contentView.bounds
        // 计算label居中位置:垂直、水平都居中
        label.frame = CGRect(
            x: 5,
            y: (contentView.bounds.height - 50) / 2,
            width: contentView.bounds.width - 10,
            height: 50
        )
    }

    override func prepareForReuse() {
        super.prepareForReuse()
        imageView.image = nil
        label.text = nil
    }

    func configure(with urlString: String, labelText: String) {
        guard let url = URL(string: urlString) else {
            return
        }
        
        let task = URLSession.shared.dataTask(with: url) { [weak self] data, _, error in
            guard let data = data, error == nil else {
                return
            }
            
            DispatchQueue.main.async {
                self?.label.text = labelText
                self?.imageView.image = UIImage(data: data)
            }
        }
        task.resume()
    }
}

内容的提问来源于stack exchange,提问作者jo1

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 08:57:00