0

콜렉션 뷰 셀의 동적 높이를 설정 한 것보다 많은 답변을 가진 주제를 본 적이 없습니다. 솔루션 중 일부는 상상할 수없는 양의 코드를 가지고 있으며, 이는 UICollectionView이 클러스터 인 컨센서스에 한층 더 기여합니다. UITableView을 사용하면 제약 조건이 제대로 연결될 때 동적 셀 높이가 구성되기 때문에 아무 것도하지 않고도이를 수행 할 수 있기 때문입니다. 그러나 나는 콜렉션 뷰에서 더 나은 핸들을 원한다. 그리고 그것은 악몽입니다.UICollectionViewCell의 동적 높이가 프로그래밍 방식으로 제약 조건을 사용합니까?

수 백 줄의 코드없이 Swift에서 컬렉션 뷰 셀의 높이를 프로그래밍 방식으로 콘텐츠 크기 (스토리 보드 없음)로 동적으로 설정하려면 어떻게해야합니까?

빈 프로젝트에 다음을 연결할 수 있으며, 그렇게 느껴지면 깨끗하게 작동합니다.

CollectionViewFlowLayout :

class CollectionViewFlowLayout: UICollectionViewFlowLayout { 

    // inits 
    override init() { 
     super.init() 

     config() 
    } 

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

    // config 
    func config() { 
     scrollDirection = .vertical 
     minimumLineSpacing = 0 
     minimumInteritemSpacing = 0 
    } 
} 

CollectionViewController

class CollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout { 

    // model properties 
    let colorArray: [UIColor] = [.red, .green, .blue, .yellow] 
    let labelArray: [String] = [ 
     "sconewolf sconewolf sconewolf sconewolf sconewolf sconewolf sconewolf sconewolf sconewolf sconewolf sconewolf sconewolf sconewolf sconewolf sconewolf sconewolf sconewolf sconewolf sconewolf sconewolf", 
     "sconewolf sconewolf sconewolf sconewolf sconewolf sconewolf sconewolf sconewolf sconewolf sconewolf sconewolf sconewolf", 
     "sconewolf sconewolf sconewolf sconewolf sconewolf sconewolf sconewolf sconewolf sconewolf sconewolf sconewolf sconewolf sconewolf sconewolf sconewolf sconewolf sconewolf sconewolf sconewolf sconewolf sconewolf sconewolf sconewolf sconewolf sconewolf sconewolf sconewolf sconewolf sconewolf sconewolf sconewolf sconewolf sconewolf sconewolf", 
     "sconewolf sconewolf sconewolf sconewolf sconewolf sconewolf sconewolf sconewolf" 
    ] 

    // view did load 
    override func viewDidLoad() { 
     super.viewDidLoad() 

     config() 
    } 

    // config 
    func config() { 
     collectionView?.dataSource = self 
     collectionView?.delegate = self 
     collectionView?.backgroundColor = UIColor.gray 
     collectionView?.contentInset = UIEdgeInsets(top: -20, left: 0, bottom: 0, right: 0) 
     collectionView?.alwaysBounceVertical = true 
     collectionView?.alwaysBounceHorizontal = false 
     collectionView?.register(CollectionViewCell.self, forCellWithReuseIdentifier: "cell1") 
    } 

    // data source: number of items in section 
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
     return colorArray.count 
    } 

    // data source: cell for item 
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 

     let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell1", for: indexPath) as! CollectionViewCell 
     cell.backgroundColor = colorArray[indexPath.item] 
     cell.label.text = labelArray[indexPath.item] 
     return cell 
    } 

    // delegate: size for item 
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { 

     return CGSize(width: view.frame.width, height: 200) 
    } 
} 

CollectionViewCell

class CollectionViewCell: UICollectionViewCell { 

    // view properties 
    var label = UILabel() 

    // inits 
    override init(frame: CGRect) { 
     super.init(frame: frame) 

     config() 
     addLabel() 
    } 

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

    // config 
    func config() { 
     self.translatesAutoresizingMaskIntoConstraints = false 
    } 

    // add label 
    func addLabel() { 
     label.font = UIFont.boldSystemFont(ofSize: 18) 
     label.textColor = UIColor.black 
     label.numberOfLines = 0 
     label.translatesAutoresizingMaskIntoConstraints = false 
     addSubview(label) 
     label.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true 
     label.topAnchor.constraint(equalTo: self.topAnchor).isActive = true 
     label.widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true 
     label.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true 
     label.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true 
     label.sizeToFit() 
    } 
} 

답변

0
this 게시물의 도움으로

, 프로그래밍 방식 동적을 만들 수 UICollectionViewCell입니다 :

self.contentView.translatesAutoresizingMaskIntoConstraints = false 

let screenWidth = UIScreen.main.bounds.size.width 

contentView.addSubview(msgLabel) 

[ 
    msgLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 8), 
    msgLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 8), 
    msgLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -8), 
    msgLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -8), 
    msgLabel.widthAnchor.constraint(equalToConstant: screenWidth - 16) 
    ].forEach{ $0.isActive = true } 
UICollectionViewCell

의있는 contentView에 UIControls를 추가

if let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout { 
    flowLayout.estimatedItemSize = CGSize(width: 1, height: 1) 
} 

:

은 UICollectionView의 레이아웃의 estimatedItemSize 다음과 같이 설정

집합 번호 울라 벨의 라인 수를 0으로 설정