【发布时间】:2021-11-14 14:33:09
【问题描述】:
我是 swift 新手 - 我想在 collectionview 中的 ui 图像视图图像上添加一个标签,但是我遇到了一些问题。文本位于图像视图下方,我如何调整它使其保持在图像中间。我想在代码中做到这一点,而不是使用故事板或 nib 文件。我相信这可能是由于我设置的框架:
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)
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)
contentView.addSubview(label)
contentView.addSubview(imageView)
}
required init?(coder: NSCoder) {
fatalError()
}
override func layoutSubviews() {
super.layoutSubviews()
label.frame = CGRect(x: 5, y: 0, width: contentView.frame.size.width-10, height: 50)
//imageView.frame = contentView.bounds
imageView.frame = CGRect(x: 0, y: 0, width: 250, height: 250)
}
override func prepareForReuse() {
super.prepareForReuse()
imageView.image = nil
}
func configure(with urlString: String, label: 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 = label
let image = UIImage(data: data)
self?.imageView.image = image
}
}
task.resume()
}
}
【问题讨论】:
-
一些事情,希望他们有所帮助。您发布的代码使用 URL - 您可以消除这些以便我可以复制吗?只是想消除一些东西。接下来,您是否尝试过任何断点?你为什么使用框架?您是否遇到了
UIViewController或UIView生命周期调用? -
我正在学习快速课程,导师使用框架来定位 ui 元素,不建议这样做吗?
标签: ios swift uicollectionview uicollectionviewcell frame