Skip to content

Instantly share code, notes, and snippets.

@mabuak
Last active June 5, 2023 13:03
Show Gist options
  • Save mabuak/d61446bdc6aba258dc29fd2f5d4dca81 to your computer and use it in GitHub Desktop.
Save mabuak/d61446bdc6aba258dc29fd2f5d4dca81 to your computer and use it in GitHub Desktop.
This is Example Code How To Make Collectionview Used Dynamic Height From this answer https://stackoverflow.com/questions/45204283/collectionview-dynamic-height-with-swift-3-in-ios
//
// TestimonyCollectionViewController.swift
// EMtrade
//
// Created by Fachruzi Ramadhan on 02/09/20.
// Copyright © 2020 Fachruzi Ramadhan. All rights reserved.
//
import UIKit
class TestimonyCollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
private let reuseIdentifier = "Cell"
//var testimonyList = [String]()
var testimonyList = [
["profile": "testimony_maryati", "testimony": "Sejak bergabung dengan Premium Access dari Ellen May Institute, invetasi saya bertumbuh. Saya berusia 47 tahun, mulai berinvestasi saham dengan menyisihkan gaji dan uang bulanan dari suami. \n Selama satu tahun berinvestasi, empat dari saham saya masing-masing menghasilkan keuntungan 90%, 130%, 300%, dan 700%. Memang, ada pula saham-saham yang sempat merugi, tetapi investasi saya secara keseluruhan menghasilkan keuntungan. Saya menyadari bahwa ada strategi untuk meminimalkan resiko dalam investasi di saham. Karena itu, saya berlangganan Premium Access dari Ellen May Institute. Hal ini sangat membantu saya dalam memilih saham yang akan saya beli.\n- Maryani"],
["profile": "testimony_imam", "testimony": "Premium Access by Ellen May Institute banyak membantu saya. Dengan mengikuti arahan dari Premium Access, beberapa saham saya untung di atas 100 persen. Alhamdulillah, dalam setahun ini saya bisa menarik dari rekening dan memberli rumah Rp. 1M sementara nilai saham masih sama seperti modal.\n-Imam Edy Suwito"],
["profile": "testimony_mian", "testimony": "Saya semakin jatuh cinta dengan trading ini. Di sela kesibukan saya sebagai dokter, walaupun saya trading dengan cara curi-curi waktu, ternyata bisa profit juga berkat bantuan Premium Access dari Ellen May Institute. Profit saya seminggu dari trading setara dengan gaji saya sebulan sebagai dokter.\n- Mian Pasaribu"],
]
override func viewDidLoad() {
super.viewDidLoad()
collectionView.backgroundColor = .white
collectionView.allowsSelection = true
if let layout = collectionViewLayout as? UICollectionViewFlowLayout {
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.estimatedItemSize = CGSize(width: collectionView.frame.width, height: 400) //530
}
collectionView.showsHorizontalScrollIndicator = false
collectionView.showsVerticalScrollIndicator = false
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Register cell classes
self.collectionView!.register(TestimonyCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
// Do any additional setup after loading the view.
}
// MARK: UICollectionViewDataSource
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return testimonyList.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! TestimonyCollectionViewCell
cell.profileIV.image = UIImage(named: testimonyList[indexPath.item]["profile"]!)!
cell.testimonyLb.text = testimonyList[indexPath.item]["testimony"]
return cell
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
}
func getHeightForLable(labelWidth: CGFloat, numberOfLines: Int = 1, labelText: String, labelFont: UIFont) -> CGFloat {
let tempLabel: UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: labelWidth, height: CGFloat.greatestFiniteMagnitude))
tempLabel.numberOfLines = numberOfLines
tempLabel.text = labelText
tempLabel.font = labelFont
tempLabel.sizeToFit()
return tempLabel.frame.height
}
}
class TestimonyCollectionViewCell: UICollectionViewCell {
let profileIV: UIImageView = {
let iv = UIImageView()
return iv
}()
let testimonyLb: UILabel = {
let lb = UILabel()
lb.textAlignment = .center
lb.font = UIFont(name: "Prompt-Regular", size: 14)
lb.textColor = UIColor(red: 0, green: 0, blue: 0, alpha: 1)
lb.numberOfLines = 0
return lb
}()
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(profileIV)
profileIV.snp.makeConstraints { (make) in
make.centerX.equalToSuperview()
make.top.equalTo(contentView).offset(5)
make.height.equalTo(100)
make.width.equalTo(100)
}
contentView.addSubview(testimonyLb)
testimonyLb.snp.makeConstraints { (make) in
make.centerX.equalTo(contentView)
make.top.equalTo(profileIV.snp.bottom).offset(20)
make.leading.equalTo(contentView).offset(30)
make.trailing.equalTo(contentView).offset(-30)
make.bottom.equalTo(contentView).offset(-40)
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
setNeedsLayout()
layoutIfNeeded()
let size = contentView.systemLayoutSizeFitting(layoutAttributes.size)
var frame = layoutAttributes.frame
frame.size.height = ceil(size.height)
layoutAttributes.frame = frame
return layoutAttributes
}
}
@mabuak
Copy link
Author

mabuak commented Sep 2, 2020

Autoloayout i'm used http://snapkit.io/docs/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment