Reputation: 83
I got UIView "statusbar
" as background inside my cell, which works like a progress-bar. The orange view is the statusbar:
THE PROBLEM
When I launch the app, the statusbar's are ascending for demo usage. BUT I just cannot change the width of the statusbar afterwards (after set in the layoutSubviews()
).
Here is my code for the cell class:
import UIKit
class MyCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var myLabel: UILabel!
@IBOutlet weak var statusbar: UIView!
var newWidth = 0
override func layoutSubviews() {
self.layer.cornerRadius = 15.0
self.layer.masksToBounds = true
statusbar.frame = CGRect(x: 0, y: 0, width: newWidth, height: Int(self.frame.height))
super.layoutSubviews()
}
}
extension MyCollectionViewCell{
func setStatusbar(completedTasks: Int, totalTasks: Int){
newWidth = Int((Double(self.frame.width) * (Double(completedTasks) / Double(totalTasks)))) //calculates new width with given tasks
//Local var attempt: (not working)
/**var frameRect = statusbar.frame;
frameRect.size.width = newWidth;
statusbar.frame = frameRect; **/
//Change CGRect attempt: (not working)
statusbar.frame = CGRect(x: 0, y: 0, width: newWidth, height: Int(self.frame.height))
//Somehow update the cells... should call layoutSubviews here?
reloadInputViews()
}
}
And in my ViewController.swift I change the statusbars width by cell.setStatusbar(completedTasks: indexPath.row, totalTasks: 47)
Here are the both important funcs from ViewController.swift, from where I want to change the statusbar:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! MyCollectionViewCell
cell.myLabel.text = self.items[indexPath.row]
cell.backgroundColor = UIColor(rgb: 0xF444444)
cell.setStatusbar(completedTasks: indexPath.row, totalTasks: 47) //Makes the statusbar increasing with every cell for testing when launched
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// handle tap events
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! MyCollectionViewCell
cell.setStatusbar(completedTasks: 47, totalTasks: 47) //Should make the statusbar to 100% (equal width as cell) for testing!
collectionview.reloadData()
}
Can someone help me... I just cannot change the with of "statusbar" (the orange UIView) :/
Thanks!
Upvotes: 2
Views: 278
Reputation: 5881
Don't call collectionview.reloadData()
in didSelectItemAt
as that's causing all of your cells to reload themself and set completedTasks
back to indexPath.row
You shouldn't need to reload the collectionview once you've called setStatusBar
, or call layoutSubviews
(you shouldn't call that directly anyway, you should use setNeedsLayout
)
Upvotes: 1