【问题标题】:UICollectionViewCell layout with multi line labels and image view breaks layout具有多行标签和图像视图的 UICollectionViewCell 布局中断布局
【发布时间】:2021-08-24 22:39:59
【问题描述】:

我目前正在尝试在 UICollectionViewCell 中完成以下布局

┌─────────────────────────────────────┐
│ ┌─────────────────────────────────┐ │
│ │                                 │ │
│ │                                 │ │
│ │                                 │ │
│ │                                 │ │
│ │                                 │ │
│ │                                 │ │
│ │                                 │ │
│ │              Image              │ │
│ │                                 │ │
│ │                                 │ │
│ │                                 │ │
│ │                                 │ │
│ │                                 │ │
│ │                                 │ │
│ │                                 │ │
│ │                                 │ │
│ └─────────────────────────────────┘ │
│ ┌─────────────────────────────────┐ │
│ │┌───────────────────────────────┐│ │
│ ││        Multiline text         ││ │
│ │└───────────────────────────────┘│ │
│ │┌───────────────────────────────┐│ │
│ ││        Multiline text         ││ │
│ │└───────────────────────────────┘│ │
│ └─────────────────────────────────┘ │
└─────────────────────────────────────┘

为此,我将UICollectionViewCell 子类化并使用自动布局创建我的布局。

// MARK: - View
class ProductCell: UICollectionViewCell {
    
    // MARK: - UI Properties    
    private lazy var imageView = UIImageView().with {
        $0.translatesAutoresizingMaskIntoConstraints = false
        $0.contentMode = .scaleAspectFill
        $0.clipsToBounds = true
        $0.layer.cornerRadius = 5
        
        $0.setContentHuggingPriority(.defaultLow, for: .vertical)
    }
   
    private lazy var productNameLabel = UILabel().with {
        $0.translatesAutoresizingMaskIntoConstraints = false
        $0.textColor = .label
        
        $0.font = UIFont.preferredFont(forTextStyle: .headline)
        
        $0.numberOfLines = 0
        $0.lineBreakMode = .byWordWrapping
    }
    
    private lazy var productDescriptionLabel = UILabel().with {
        $0.translatesAutoresizingMaskIntoConstraints = false
        $0.textColor = .secondaryLabel
        
        $0.numberOfLines = 0
        $0.lineBreakMode = .byWordWrapping
    }
    
    // MARK: - Initializers
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupView()
    }
    
    required init?(coder: NSCoder) {
        fatalError("Not happening")
    }
}

// MARK: - View Setup
extension ProductCell {
    private func setupView() {
    
        contentView.addSubview(imageView)
        contentView.addSubview(productNameLabel)
        contentView.addSubview(productDescriptionLabel)
        
        NSLayoutConstraint.activate([
            imageView.topAnchor.constraint(equalTo: contentView.topAnchor),
            imageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
            imageView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),

            productNameLabel.topAnchor.constraint(equalTo: imageView.bottomAnchor, constant: 10),
            productNameLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
            productNameLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
            
            productDescriptionLabel.topAnchor.constraint(equalTo: productNameLabel.bottomAnchor, constant: 5),
            productDescriptionLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
            productDescriptionLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
            productDescriptionLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
        ])
    }
}

with 扩展只是一种方便的方法,可以让UIViews 的创建更加干净。我已经尝试了几种配置和/或自动布局配置,但我找不到两个标签都支持多行并且图像仍然可见的解决方案。

所以我想要实现的是,如果两个标签需要更多空间以防标签中有更多行,则图像可以缩小。此外,标签应始终可见。用sn -p 看到的配置我只能达到下面的结果。我做了单元格.systemTeal的背景,表示图片下方有2个标签。

这是通过添加一些虚拟数据来做一些调试来实现的

// MARK: - View configuration
extension ProductCell {
    func configure() {
        imageView.image = UIImage(named: "test_image_2")
        
        productNameLabel.text = "This is a ridicoulus long text lets see what is happening"
        productDescriptionLabel.text = "This is a ridicoulus long text lets see what is happening"
    }
}

当我查看 Xcode 的运行时问题时,它告诉我

Layout Issues: Height is ambiguous for UIImageView.

Layout Issues: Height and vertical position are ambiguous for UILabel - This is a ridiculous long text lets see what is happening.

Layout Issues: Height and vertical position are ambiguous for UILabel - This is a ridicoulus long text lets see what is happening.

我知道布局系统似乎没有足够的信息来正确确定两个标签的高度,但我不知道为什么它缺少这些信息。 非常感谢任何帮助。

【问题讨论】:

  • 尝试为图像高度限制设置较低的 heightPriority。

标签: ios swift uicollectionview uicollectionviewcell


【解决方案1】:

如果我理解得很好,这是您的代码的示例:

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

let tableView = UITableView()

override func viewDidLoad() {
    super.viewDidLoad()
    
    view.backgroundColor = .white
    
    tableView.delegate = self
    tableView.dataSource = self
    tableView.register(MyCell.self, forCellReuseIdentifier: "cellId")
    tableView.translatesAutoresizingMaskIntoConstraints = false
    
    view.addSubview(tableView)
    tableView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
    tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
    tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
    tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 3
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableView.automaticDimension
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath) as! MyCell
    
    return cell
 }
}

这是你的自定义单元格:

class MyCell: UITableViewCell {

let myImageView: UIImageView = {
    
    let iv = UIImageView()
    iv.contentMode = .scaleAspectFit
    iv.clipsToBounds = true
    iv.backgroundColor = .red
    iv.layer.cornerRadius = 8
    iv.clipsToBounds = true
    iv.translatesAutoresizingMaskIntoConstraints = false
    
    return iv
}()

let label1: UILabel = {
    let l = UILabel()
    l.text = "Multiline 1\nMultiline1 second line"
    l.font = .systemFont(ofSize: 20, weight: .bold)
    l.textColor = .black
    l.textAlignment = .center
    l.backgroundColor = .clear
    l.numberOfLines = 0
    l.adjustsFontSizeToFitWidth = true
    
    return l
}()

let label2: UILabel = {
    let l = UILabel()
    l.text = "Multiline 2\nMultiline1 second line"
    l.font = .systemFont(ofSize: 20, weight: .bold)
    l.textColor = .black
    l.textAlignment = .center
    l.backgroundColor = .clear
    l.numberOfLines = 0
    l.adjustsFontSizeToFitWidth = true
    
    return l
}()

override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)
    
    myImageView.backgroundColor = .red
    myImageView.translatesAutoresizingMaskIntoConstraints = false
    
    let stackView = UIStackView(arrangedSubviews: [label1, label2])
    stackView.distribution = .fill
    stackView.axis = .vertical
    stackView.spacing = 8
    stackView.translatesAutoresizingMaskIntoConstraints = false
    
    contentView.addSubview(myImageView)
    myImageView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 10).isActive = true
    myImageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 10).isActive = true
    myImageView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -10).isActive = true
    myImageView.heightAnchor.constraint(equalTo: myImageView.widthAnchor).isActive = true
    
    contentView.addSubview(stackView)
    stackView.topAnchor.constraint(equalTo: myImageView.bottomAnchor, constant: 10).isActive = true
    stackView.leadingAnchor.constraint(equalTo: myImageView.leadingAnchor).isActive = true
    stackView.trailingAnchor.constraint(equalTo: myImageView.trailingAnchor).isActive = true
    stackView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: 0).isActive = true
}

required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }
}

这是结果

【讨论】:

    【解决方案2】:

    您可以使用 setContentCompressionResistancePriority 函数来设置 UIlabel 和 UIImage 的内容优先级。 productNameLabel.setContentCompressionResistancePriority(UILayoutPriority.init(900), for: NSLayoutConstraint.Axis.horizontal) productDescriptionLabel.setContentCompressionResistancePriority(UILayoutPriority.init(900), for: NSLayoutConstraint.Axis.horizontal) imageView.setContentCompressionResistancePriority(UILayoutPriority.init(200), for: NSLayoutConstraint.Axis.horizontal)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多