iOS UITableViewCell中intrinsicCon

2022-12-09  本文已影响0人  迷路的小小
  1. SnowTagsView
  2. 通常情况下使用intrinsicContentSize的cell无法自动刷新高度
class TableViewCell: UITableViewCell {
    let tagsView = SnowTagsView()
    
    override func prepareForReuse() {
        super.prepareForReuse()
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupUI()
    }
    
    func setupUI() {
        contentView.addSubview(tagsView)
        tagsView.translatesAutoresizingMaskIntoConstraints = false
        contentView.addConstraints([
            tagsView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 20),
            tagsView.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 20),
            tagsView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -20),
            tagsView.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -20)
        ])
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
}

此时,显示是单行,高度并没有刷新。

  1. contentSize
    想要解决这个问题,首先要从UITableViewcontentSize入手。
  1. 解决之道
    由此可以在tableView计算contentSize的时候刷新cell布局
    override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize {
        tagsView.layoutIfNeeded()
        return super.systemLayoutSizeFitting(targetSize, withHorizontalFittingPriority: horizontalFittingPriority, verticalFittingPriority: verticalFittingPriority)
    }
上一篇 下一篇

猜你喜欢

热点阅读