I am looking to make my xib custom collection view cell height dynamic when clicked upon rather than using a fixed variable height.
I have tried using constraints on the heights of the cell in the storyboard.
This is the MotCollectionViewCell.swift code:
import UIKit
protocol ExpandedCellDelegate:NSObjectProtocol{
func topButtonTouched(indexPath:IndexPath)
}
class MotCollectionViewCell: UICollectionViewCell {
#IBOutlet var heightConstraint: NSLayoutConstraint!
#IBOutlet var topButton: UIButton!
weak var delegate:ExpandedCellDelegate?
public var indexPath:IndexPath!
#IBAction func topButtonTouched(_ sender: UIButton) {
if let delegate = self.delegate{
delegate.topButtonTouched(indexPath: indexPath)
}
}
#IBOutlet var testLbl: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
}
This is the BarChartViewControllerCell.Swift code :
import UIKit
import Charts
class BarChartViewController: UIViewController, ChartViewDelegate, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, ExpandedCellDelegate {
// Bar Chart Properties
#IBOutlet var barChartView: BarChartView!
var dataEntry: [BarChartDataEntry] = []
// Chart Data
var result = [String]()
var mileage = [String]()
var colours = [UIColor]()
var list = [Tester]()
// Collection View properties
#IBOutlet var collectionView: UICollectionView!
var expandedCellIdentifier = "MotCollectionViewCell"
var cellWidth:CGFloat{
return collectionView.frame.size.width
}
var expandedHeight : CGFloat = 258
var notExpandedHeight : CGFloat = 75
var dataSource = ["data0","data1","data2","data3","data4"]
var isExpanded = [Bool]()
override func viewDidLoad() {
super.viewDidLoad()
isExpanded = Array(repeating: false, count: dataSource.count)
//Register nib cell
let nibCell = UINib(nibName: expandedCellIdentifier, bundle: nil)
collectionView.register(nibCell, forCellWithReuseIdentifier: expandedCellIdentifier)
}
// Collection View functions
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return dataSource.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: expandedCellIdentifier, for: indexPath) as! MotCollectionViewCell
cell.indexPath = indexPath
cell.delegate = self
//configure Cell
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if isExpanded[indexPath.row] == true{
return CGSize(width: cellWidth, height: expandedHeight)
}else{
return CGSize(width: cellWidth, height: notExpandedHeight)
}
}
func topButtonTouched(indexPath: IndexPath) {
isExpanded[indexPath.row] = !isExpanded[indexPath.row]
UIView.animate(withDuration: 0.8, delay: 0.0, usingSpringWithDamping: 0.9, initialSpringVelocity: 0.9, options: UIView.AnimationOptions.curveEaseInOut, animations: {
self.collectionView.reloadItems(at: [indexPath])
}, completion: { success in
print("success")
})
}
}
When the cell is clicked, the cell expands to the height which I declared as a constant, what I am trying to achieve is have the cell expand according to the data within it.
Related
Working Example Video
I am trying to create an onboarding view such as Instagram stories with a progress bar on top of the view.
So far I was able to animate to the second or third index in the given time. This animation also changes stack view progress bar. But when I try to scroll to the next or previous collection view index I can not show this action inside the progress bar.
I can read the current page index with page control but can not reflect this reading to progress bar.
class OnboardingViewController: UIViewController, SegmentedProgressBarDelegate {
#IBOutlet weak var collectionView: UICollectionView!
#IBOutlet weak var stackView: UIStackView!
private var spb: SegmentedProgressBar!
var currentPage = 0
lazy var pageControl: UIPageControl = {
let pageControl = UIPageControl()
pageControl.numberOfPages = slides.count
return pageControl
}()
//Burası Presenter'dan gelecek.
var slides: [OnboardingSlide] = [
OnboardingSlide(title: "Delicious Dishes", image: #imageLiteral(resourceName: "1")),
OnboardingSlide(title: "World-Class Chefs", image: #imageLiteral(resourceName: "2")),
OnboardingSlide(title: "Instant World-Wide Delivery", image: #imageLiteral(resourceName: "3"))
]
override func viewDidLoad() {
super.viewDidLoad()
spb = SegmentedProgressBar(numberOfSegments: slides.count, duration: 3)
spb.frame = CGRect(x: 15, y: 56, width: collectionView.frame.width - 30, height: 4)
spb.delegate = self
spb.topColor = UIColor.white
spb.bottomColor = UIColor.white.withAlphaComponent(0.25)
spb.padding = 2
collectionView.delegate = self
collectionView.dataSource = self
stackView.addArrangedSubview(spb)
spb.startAnimation()
collectionView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tappedView)))
}
func segmentedProgressBarChangedIndex(index: Int) {
updateView(index: index)
}
override var prefersStatusBarHidden: Bool {
return true
}
func segmentedProgressBarFinished() {
print("Finished!")
}
#objc private func tappedView() {
spb.isPaused = !spb.isPaused
}
private func updateView(index: Int) {
print("index: \(index)")
let indexPath = IndexPath(row: index, section: 0)
collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
}
#IBAction func loginButtonTapped(_ sender: UIButton) {
}
#IBAction func signupButtonTapped(_ sender: UIButton) {
}
}
extension OnboardingViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return slides.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: OnboardingCollectionViewCell.identifier, for: indexPath) as! OnboardingCollectionViewCell
cell.setup(slides[indexPath.row])
return cell
}
}
extension OnboardingViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.frame.width, height: collectionView.frame.height)
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let width = scrollView.frame.width
currentPage = Int(scrollView.contentOffset.x / width)
pageControl.currentPage = currentPage
updateView(index: currentPage)
print("current page: \(currentPage)")
}
}
I have used
https://github.com/D-32/SegmentedProgressBar
as the segmentedProgressBar
class OnboardingCollectionViewCell: UICollectionViewCell {
static let identifier = String(describing: OnboardingCollectionViewCell.self)
#IBOutlet weak var slideImageView: UIImageView!
#IBOutlet weak var slideTitleLabel: UILabel!
func setup(_ slide: OnboardingSlide) {
slideImageView.image = slide.image
slideTitleLabel.text = slide.title
}
}
struct OnboardingSlide {
let title: String
let image: UIImage
}
extension OnboardingViewController: UICollectionViewDelegateFlowLayout {
func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) {
if scrollView.panGestureRecognizer .translation(in: view).x > 0 {
spb.rewind()
} else {
spb.skip()
}
}
}
with this, I was able to understand if collection view was scrolled left or right. Thus calling related functions inside the spb does the trick.
I am trying this for a couple of days now and haven't achieved anything yet. What I am trying to do is when a user picks a User item form the ViewController class, I want to save it in Realm and show it in the CollectionView of the SavedInterestsViewController class. I use a delegate pattern as suggested in this post How to access and refresh a UITableView from another class in Swift, but unfortunately I still receive nil, I guess because the GC removed the collectionView outlet already right? (please correct me if I misunderstood it). However, how can I get this to work by using a delegate pattern? Here is my code, this is the class where the user Picks a new User-item:
protocol ViewControllerDelegate {
func didUpdate(sender: ViewController)
}
class ViewController: UIViewController {
#IBOutlet weak var searchBar: UISearchBar!
#IBOutlet weak var collectionView: UICollectionView!
var delegate: ViewControllerDelegate?
let numberOfTweets = 5
let realm = try! Realm()
var image = UIImage()
var imageArray: [String] = []
var userArray: [User] = []
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(UINib(nibName: "CollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "CollectionCell")
searchBar.delegate = self
}
}
extension ViewController: UISearchBarDelegate {
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
print("One second...")
let functionClass = NetworkingFunctions()
var loopCount = 0
functionClass.getWikipediaAssumptions(for: searchBar.text!) { [self] (articleArray) in
self.userArray.removeAll()
for x in articleArray {
functionClass.performWikipediaSearch(with: x, language: WikipediaLanguage("en")) { (user) in
self.userArray.append(user)
collectionView.reloadData()
loopCount += 1
}
}
}
}
}
extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return userArray.count
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionCell", for: indexPath) as! CollectionViewCell
let image = UIImage.init(data: userArray[indexPath.item].image as Data)
cell.userImage.image = image
cell.nameLabel.text = userArray[indexPath.item].name
cell.userImage.layer.borderColor = image?.averageColor?.cgColor
if userArray[indexPath.item].checked == false {
cell.checkmark.isHidden = true
} else {
cell.checkmark.isHidden = false
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if userArray[indexPath.item].checked == false {
userArray[indexPath.item].checked = true
collectionView.reloadData()
let newUser = User()
newUser.image = userArray[indexPath.item].image
newUser.name = userArray[indexPath.item].name
newUser.checked = true
try! realm.write {
realm.add(newUser)
}
self.delegate = SavedInterestsViewController()
self.delegate?.didUpdate(sender: self)
}
else {
userArray[indexPath.item].checked = false
collectionView.reloadData()
}
}
}
extension ViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = UIScreen.main.bounds.width/3 - 10
let height = width
return CGSize(width: width, height: height)
}
}
class User: Object {
#objc dynamic var image: NSData = NSData()
#objc dynamic var name: String = ""
#objc dynamic var checked: Bool = false
}
... and this is the class where I want to show the selected item, after the User clicked on the 'Back' Button of the navigation controller of the ViewController class:
class SavedInterestsViewController: UIViewController, ViewControllerDelegate {
func didUpdate(sender: ViewController) {
DispatchQueue.main.async {
self.collectionView.reloadData()
}
}
#IBOutlet weak var addButton: UIBarButtonItem!
#IBOutlet weak var collectionView: UICollectionView!
let realm = try! Realm()
var userArray: [User] = []
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(UINib(nibName: "CollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "CollectionCell")
fetchDataFromRealm()
}
#IBAction func addButtonPressed(_ sender: UIBarButtonItem) {
performSegue(withIdentifier: "SavedToNew", sender: self)
}
func fetchDataFromRealm() {
userArray.append(contentsOf: realm.objects(User.self))
collectionView.reloadData()
}
}
extension SavedInterestsViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return userArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionCell", for: indexPath) as! CollectionViewCell
let image = UIImage.init(data: userArray[indexPath.item].image as Data)
cell.userImage.image = image
cell.nameLabel.text = userArray[indexPath.item].name
cell.userImage.layer.borderColor = image?.averageColor?.cgColor
if userArray[indexPath.item].checked == false {
cell.checkmark.isHidden = true
} else {
cell.checkmark.isHidden = false
}
return cell
}
}
extension SavedInterestsViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = UIScreen.main.bounds.width/3 - 10
let height = width
return CGSize(width: width, height: height)
}
}
in your code you have lines
self.delegate = SavedInterestsViewController()
self.delegate?.didUpdate(sender: self)
but it do mostly nothing - you set the delegate to newly created class, didUpdate it - but I don't see any use of it - you don't present it in any way.
If I understand you right - you have SavedInterestsViewController, from it - you open ViewController, do something and when back to SavedInterestsViewController. (I can be wrong with your flow - correct me if so)
In this flow - you have delegate property in ViewController, but it must be of type SavedInterestsViewController. And you have to set it to SavedInterestsViewController when you open ViewController from it. And later in ViewController you have to call didUpdate method of delegate.
I have a mini game in Single-view-app project with item inventory (CollectionView). Its structure in main.Storyboard: CollectionView -> cell -> ContentView -> inventoryImageView. When the game starts items.count of empty cells are generated. Whenever a user taps on imageView of an item he finds, I want this imageView to populate the most left and available cell of the inventory. Something like:
cell.inventoryImageView = itemImageView
How can I access this left unpopulated cell?
The code is:
struct Items {
let imageName: String
var location = (0, 0)
}
var key = Items(imageName: "icons8-key-50")
var chest = Items(imageName: "icons8-closed-treasure-chest-50")
var rock = Items(imageName: "icons8-rock-50")
var bone = Items(imageName: "icons8-human-bone-50")
var mushroom = Items(imageName: "icons8-mushroom-50")
var items = [Items]()
override func viewDidLoad() {
items = [key, chest, rock, bone, mushroom]
}
when user clicks Start button this func gets triggered for every item :
func createItems(imageName: String) {
let imageNamePNG = "\(imageName).png"
let itemImage = UIImage(named: imageNamePNG)
let itemImageView = UIImageView(image: itemImage) itemImageView.frame = CGRect(x: 70, y: 0, width: 63, height: 63)
itemImageView.frame = CGRect(x: Int.random(in: 70...294), y: Int.random(in: 100...543), width: 63, height: 63)
view.addSubview(itemImageView)
createdImages.append(itemImageView)
}
cell creation part:
// MARK: - UICollectionViewDataSource protocol
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.items.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! CollectionViewCell
return cell
}
I don't quite understand what you want to do but I hope this code could help you.
CustomCollectionViewCell.swift
import UIKit
class CustomCollectionViewCell: UICollectionViewCell {
#IBOutlet weak var inventoryImageView: UIImageView!
}
ViewController.swift
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var collectionView: UICollectionView!
#IBOutlet weak var imageButton: UIButton!
var key = Items(imageName: "img-1")
var chest = Items(imageName: "img-2")
var rock = Items(imageName: "img-3")
var bone = Items(imageName: "img-4")
var mushroom = Items(imageName: "img-5")
var items = [Items]()
var index = 0
var createdImages = [Items]()
override func viewDidLoad() {
super.viewDidLoad()
self.items = [key, chest, rock, bone, mushroom]
self.imageButton.setImage(UIImage(named: self.items[index].imageName), for: .normal)
}
#IBAction func imageButtonAction(_ sender: Any) {
index += 1
if index >= items.count{
index = 0
}
self.imageButton.setImage(UIImage(named: self.items[index].imageName), for: .normal)
self.createdImages.append(self.items[index])
self.collectionView.reloadData()
}
}
extension ViewController: UICollectionViewDataSource, UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.createdImages.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CustomCollectionViewCell
cell.inventoryImageView.image = UIImage(named: self.createdImages[indexPath.item].imageName)
return cell
}
}
Items.swift
struct Items {
let imageName: String
var location = (0, 0)
}
i want to show 3 images in a row of a uitableview. but if i have more than 3; it should in next row of table.
Here is the Code
var abc = fileimage.count
for i in 0..<abc
{
var tempimage = UIImage(named: fileimage[i])
var actualwidth = UIScreen.main.bounds.width - 32
var noofitem = actualwidth/100
imageview.addSubview(fileimageview)
fileimageview.easy.layout(Height(<=100))
fileimageview.easy.layout(Width(<=100))
fileimageview.easy.layout(Top(0),Left(0 * CGFloat(i) * 100),Bottom(0))
fileimageview.image = tempimage
}
Here is an example of a CollectionView with grid layout.
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
var fileimage = [UIImage]()
#IBOutlet weak var showPhotosCollectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
self.showPhotosCollectionView.delegate = self
self.showPhotosCollectionView.dataSource = self
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return fileimage.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as? Cell
cell!.imageView.image = self.fileimage[indexPath.row]
return cell!
}
}
extension ViewController : UICollectionViewDelegateFlowLayout {
//1
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout:
UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let screenSize: CGRect = UIScreen.main.bounds
let screenWidth = screenSize.width
return CGSize(width: (screenWidth/3)-6, height: (screenWidth/3)-6);
}
}
Here is the example you can achieve by dividing the width of your collection view by 3.
class ViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
#IBOutlet weak var collectionViewFlowLayoutAction: UICollectionViewFlowLayout!
#IBOutlet weak var otherProvidersCollectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
//Customize these properties per your need
collectionViewFlowLayoutAction.itemSize = CGSize(width: otherProvidersCollectionView.frame.size.width/3.0, height: otherProvidersCollectionView.frame.size.width/3.0) // this will show only 3 grid per row according to your collectionview width.
collectionViewFlowLayoutAction.minimumInteritemSpacing = 1.5
collectionViewFlowLayoutAction.minimumLineSpacing = 1.8
collectionViewFlowLayoutAction.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 10, right: 0)
otherProvidersCollectionView!.collectionViewLayout = collectionViewFlowLayoutAction
}
}
I'm trying to implement flip animation in UICollectionViewCell. I have done it with 2 types of images. But I don't know how to implement it in array of images. The logic now:
but I want logic like this:
this is my code:
import UIKit
class CollectionViewCell: UICollectionViewCell {
#IBOutlet weak var coImage: UIImageView!
let cardBackTag = 0
let cardFrontTag = 1
var cardViews: (frontView: UIImageView, backView: UIImageView)?
var imgViewFront: UIImageView!
var imgViewBack: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
imgViewFront = self.createCardWithImage(imageName: "1", tag: self.cardFrontTag)
imgViewBack = self.createCardWithImage(imageName: "2", tag: self.cardBackTag)
cardViews = (frontView: imgViewFront, backView: imgViewBack)
contentView.addSubview(imgViewBack)
}
private func createCardWithImage(imageName: String, tag: Int) -> UIImageView {
let newCardImageView = UIImageView(frame: self.frame)
newCardImageView.image = UIImage(named: imageName)
newCardImageView.tag = tag
return newCardImageView
}
func flipCardAnimation(indexPath: IndexPath) {
if (imgViewBack.superview != nil) {
cardViews = (frontView: imgViewFront, backView: imgViewBack)
}else{
cardViews = (frontView: imgViewBack, backView: imgViewFront)
}
let transitionOptions = UIViewAnimationOptions.transitionFlipFromLeft
UIView.transition(with: self.contentView, duration: 1.0, options: transitionOptions, animations: {
self.cardViews!.backView.removeFromSuperview()
self.contentView.addSubview(self.cardViews!.frontView)
}, completion: { finished in
print(indexPath)
})
}
}
and
import UIKit
class CollectionViewController: UICollectionViewController {
var reuseIdentifier = "CollectionViewCell"
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView!.register(UINib(nibName: "CollectionViewCell", bundle: nil), forCellWithReuseIdentifier: reuseIdentifier)
}
// MARK: UICollectionViewDataSource
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 8
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell
return cell
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath) as! CollectionViewCell
cell.flipCardAnimation(indexPath: indexPath)
}
}
Please, help me to implement this logic! Thank you a lot!!