I want to have a uiview as cell background with changing width. This should be used as a progress-/ statusbar.
The problem:
I can’t change the width of the statusbar from my collectionViewController (only from the CollectionViewCellController)....
I manually set the width to 5 in layoutSubviews(). Then I changed it to 80 in setStatusBar(...) which I called in the other class. The width stays at 5 :(
Here is my code
import UIKit
class MyCollectionViewCell: UICollectionViewCell {
#IBOutlet weak var myLabel: UILabel!
#IBOutlet weak var statusbar: UIView!
override func layoutSubviews() {
// cell rounded section
self.layer.cornerRadius = 15.0
self.layer.masksToBounds = true
super.layoutSubviews()
statusbar.frame = CGRect(x: 0, y: 0, width: 5, height: self.frame.height)
}
}
extension MyCollectionViewCell{
func setStatusbar(completedTasks: Int, totalTasks: Int){
print(self.frame.width)
let newWidth = 80 //(self.frame.width * (CGFloat(completedTasks / totalTasks)))
statusbar.backgroundColor = .orange
statusbar.frame = CGRect(x: 0, y: 0, width: newWidth, height: Int(self.frame.height))
reloadInputViews()
}
}
And this is where I call the function setStatusbar(...) - where I want to change the width, but DOESNT work:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// get a reference to our storyboard cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! MyCollectionViewCell
// Use the outlet in our custom class to get a reference to the UILabel in the cell
cell.myLabel.text = self.items[indexPath.row] // The row value is the same as the index of the desired text within the array.
cell.backgroundColor = UIColor(rgb: 0xF444444)
cell.setStatusbar(completedTasks: 5, totalTasks: 25) //!!! HERE !!!
return cell
}
Can someone help me find the problem why the statusbar uiview doesn’t change its with from 5 to 80?
Thank you!
Related
I have a collection view with a custom layout and a diffable datasource. I would like to resize the cells with an animation.
With a custom layout: it looks like the content of the cells scaled to the new size during the animation. Only when the cells reaches its final size, it is finally redrawn (see animation below)
With a stock flow layout the subviews are laid out correctly during the animation: the label remains at the top, no resizing and same for the switch.
So I would assume that the issue is in the layout implementation, what could be added to the layout allow a correct layout during the animation?
Description
The custom layout used in this example is FSQCollectionViewAlignedLayout, I also got it with the custom I used in my code. I noticed that for some cases, it is important to always return the same layout attributes objects, which FSQCollectionViewAlignedLayout doesn't do. I modified it to not return copies, and the result is the same.
For the cells (defined in the xib), the contentMode of the cell and its contentView are set to .top. The cell's contentView contains 2 subviews: a label (laid out in layoutSubviews) and a switch (laid out with constraints, but its presence has no effect on the animation).
The code of the controller is:
class ViewController: UIViewController, UICollectionViewDelegateFlowLayout {
enum Section {
case main
}
#IBOutlet weak var collectionView : UICollectionView!
var layout = FSQCollectionViewAlignedLayout()
var dataSource : UICollectionViewDiffableDataSource<Section, String>!
var cellHeight : CGFloat = 100
override func loadView() {
super.loadView()
layout.defaultCellSize = CGSize(width: 150, height: 100)
collectionView.setCollectionViewLayout(layout, animated: false) // uncommented to use the stock flow layout
dataSource = UICollectionViewDiffableDataSource(collectionView: collectionView, cellProvider: { cv, indexPath, item in
guard let cell = cv.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as? Cell else { return nil }
cell.label.text = item
return cell
})
var snapshot = NSDiffableDataSourceSnapshot<Section, String>()
snapshot.appendSections([.main])
snapshot.appendItems(["1", "2"], toSection: .main)
dataSource.apply(snapshot)
}
override func viewDidLoad() {
super.viewDidLoad()
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 150, height: cellHeight)
}
#IBAction func resizeAction(_ sender: Any) {
if let layout = collectionView.collectionViewLayout as? FSQCollectionViewAlignedLayout {
UIView.animate(withDuration: 0.25) {
layout.defaultCellSize.height += 50
let invalidation = FSQCollectionViewAlignedLayoutInvalidationContext()
invalidation.invalidateItems(at: [[0, 0], [0, 1]])
layout.invalidateLayout(with: invalidation)
self.view.layoutIfNeeded()
}
}
if let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
UIView.animate(withDuration: 0.25) {
self.cellHeight += 50
let invalidation = UICollectionViewFlowLayoutInvalidationContext()
invalidation.invalidateItems(at: [[0, 0], [0, 1]])
layout.invalidateLayout(with: invalidation)
self.view.layoutIfNeeded()
}
}
}
}
class Cell : UICollectionViewCell {
#IBOutlet weak var label: UILabel!
override func layoutSubviews() {
super.layoutSubviews()
label.frame = CGRect(x: 0, y: 0, width: bounds.width, height: 30)
}
}
I spent a developer support ticket on this question. The answer was that custom animations when reloading cells are not supported.
So as a workaround, I ended up creating new cells instances that I add to the view hierarchy, then add autolayout constraints so that they overlap exactly the cells being resized. The animation is then run on those newly added cells. At the end of the animation, these cells are removed.
in my prototype cell I have a horizontal stack view and I connected that to my UITableViewCell and I defined an update function In my UITableViewCell that adds multiple images to the stack view and I called the function In TableViewController cellForRowAt but nothing nothing happens.
//inside UITableViewCell
#IBOutlet weak var lineStack: UIStackView!
func update(_ imageName: String){
let numberOfCopies = Int(deviceWidth/50)
let startX = (Int(deviceWidth) - (numberOfCopies*50))/2
xValue = xValue + startX
let image = UIImage(named: imageName)
for _ in 1...Int(numberOfCopies) {
xValue = xValue + heightValue
let imageView = UIImageView(image: image)
imageView.frame = CGRect(x: xValue , y: 0, width: widthValue, height: heightValue)
lineStack.addSubview(imageView)
}
}
//inside TableViewController
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Line", for: indexPath) as! LineTableViewCell
let imageName = imagesName[indexPath.row]
cell.update(imageName)
return cell
}
Your post indicates you want your images to be 50 x 50 points... use auto-layout constraints with .addArrangedSubview():
class TestCell: UITableViewCell {
#IBOutlet var lineStack: UIStackView!
func update(_ imageName: String) {
let numberOfCopies = Int(deviceWidth/50)
let image = UIImage(named: imageName)
for _ in 1...Int(numberOfCopies) {
let imageView = UIImageView(image: image)
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.widthAnchor.constraint(equalToConstant: 50).isActive = true
imageView.heightAnchor.constraint(equalTo: imageView.widthAnchor).isActive = true
lineStack.addArrangedSubview(imageView)
}
}
}
EDIT Sample result, with stack view centered horizontally:
Stack view is set to:
Axis: Horizontal
Alignment: Fill
Distribution: Fill
Spacing: 0
and this is the layout with constraints:
Note that the stack view has a Width constraint of 10, but its Priority is 250 ... that allows the stack view to stretch horizontally, while keeping IB satisfied with the constraints.
For the line:
lineStack.addSubview(imageView)
Instead of addSubview() you need to do it with addArrangedSubview(). The former is the regular way of adding a subview to a view, whereas the latter is specifically for UIStackView and tells the view to insert it properly.
I am trying to programatically size the collection cell to be the width of the frame, however, the cell size doesn't change when I run the app. Is this the right function to call for Swift 4 and Xcode 9?
import UIKit
class SettingsLauncher: NSObject, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewFlowLayout {
let blackView = UIView()
let collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
cv.backgroundColor = UIColor.white
return cv
}()
let cellID = "cell"
#objc func showMenu() {
// Show menu
if let window = UIApplication.shared.keyWindow { // Get the size of the entire window
blackView.backgroundColor = UIColor(white: 0, alpha: 0.5)
let height: CGFloat = 200
let y = window.frame.height - height // The y value to appear at the bottom of the screen
collectionView.frame = CGRect(x: 0, y: window.frame.height, width: window.frame.width, height: height)
// Add gesture recognizer on black view to dismiss menu
blackView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleDismiss)))
window.addSubview(blackView)
window.addSubview(collectionView)
blackView.frame = window.frame
blackView.alpha = 0
// Slow the animation down towards the end (curveEasOut)
UIView.animate(withDuration: 1, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
// Animate black view
self.blackView.alpha = 1
// Animate collection view
self.collectionView.frame = CGRect(x: 0, y: y, width: self.collectionView.frame.width, height: height)
}, completion: nil)
}
}
#objc func handleDismiss() {
// Dimisses menu view
UIView.animate(withDuration: 0.5) {
self.blackView.alpha = 0
if let window = UIApplication.shared.keyWindow {
self.collectionView.frame = CGRect(x: 0, y: window.frame.height, width: self.collectionView.frame.width, height: self.collectionView.frame.height)
}
}
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 6
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath)
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.frame.width, height: 50)
}
override init() {
super.init()
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(MenuCell.self, forCellWithReuseIdentifier: cellID)
}
}
Edit:
This table view is being animated from the bottom of the page and presents a collection view, which is being called from the view controller that is using the pop up menu.
I now get the error:
Multiple inheritance from classes 'NSObject' and 'UICollectionViewFlowLayout'
UICollectionViewFlowLayout is not a protocol, it's a class. You need to use UICollectionViewDelegateFlowLayout instead of UICollectionViewFlowLayout.
Change
class SettingsLauncher: NSObject, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewFlowLayout
to
class SettingsLauncher: NSObject, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout
I am adding an UIView inside my custom UITableView to draw more or less like an availability bar. I have two problems with it:
1.- The view only gets drawn when the new cells appear on screen not at launch time as you can see in the GIF below.
2.- When scrolling tableView several times the UIView on each cell is redrawn so they overlap with each other
GIF
Code of UITableViewCell :
import UIKit
class CustomTableViewcell: UITableViewCell {
#IBOutlet weak var bikeStationLabel: UILabel!
#IBOutlet weak var progressView: UIView!
#IBOutlet weak var distanceLabel: UILabel!
override internal func awakeFromNib() {
}
}
I think nothing is wrong there, it's simple. My problem I think comes with the func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell method. What I have so far is:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: CustomTableViewcell! = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CustomTableViewcell
cell.backgroundColor = UIColor(red: 120/255, green: 120/255, blue: 120/255, alpha: 0.5)
// Dump the data into a single variable to shorten the code
let stations = parsedData[indexPath.row]
// Draw a rectangle on each progress bar depending on the availability of the bikes
let availabilityGraph = UIBezierPath(roundedRect: CGRect(x: cell.progressView.frame.minX, y: cell.progressView.frame.minY, width: CGFloat(Float(stations.freeBikes!) / (Float(stations.freeBikes!) + Float(stations.freeDocks!))) * cell.progressView.frame.width, height: cell.progressView.frame.height), cornerRadius: 0)
let shapeLayer = CAShapeLayer()
shapeLayer.path = availabilityGraph.cgPath
//change the fill color
shapeLayer.fillColor = UIColor.clear().cgColor
//you can change the line width
shapeLayer.lineWidth = cell.frame.height
shapeLayer.strokeColor = UIColor(red: 96/255, green: 96/255, blue: 96/255, alpha: 0.8).cgColor
cell.progressView.layer.addSublayer(shapeLayer)
cell.bikeStationLabel.textColor = UIColor.white()
cell.bikeStationLabel.text = stations.stationName!
cell.distanceLabel.text = "100 m"
return cell
}
First of all give your layer specific name like this
shapeLayer.name = "ShapeLayer"
Now before adding it the progressView check that layer is not already added in the progressView, if added then just remove it.
if let sublayers = cell.progressView.layer.sublayers {
for layer: CALayer in sublayers {
if (layer.name == "ShapeLayer") {
layer.removeFromSuperlayer()
break
}
}
}
//Now add the layer to `progressView`
cell.progressView.layer.addSublayer(shapeLayer)
I'm new in IOS. I try to create view images app that show fullscreen size images can zoom and when user zoom out images smaller than fullscreen size, image return fullscreen size and my idea is use UICollectionView set paging Enable , scrollDirection Horizontal. So my FlowLayout will be like this
var screenSize: CGRect!
override func viewDidLoad() {
super.viewDidLoad()
screenSize = UIScreen.mainScreen().bounds
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
layout.itemSize = CGSize(width: screenSize.width, height: screenSize.height)
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
self.collectionView!.collectionViewLayout = layout
self.view.addSubview(collectionView!)
my CollectionViewCell identifier name "Cell" I drag ScrollView in it and drag image in that ScrollView
I outlet that two item in my CollectionViewCell Class like this
import UIKit
class MyCollectionCell: UICollectionViewCell, UIScrollViewDelegate{
#IBOutlet weak var scrollCell: UIScrollView!
#IBOutlet weak var imgTest: UIImageView!
}
next step in CollectionViewController set my dummy image something like this
var imageName:[String] = ["audi.png", "benz.png", "flok.png", "audi.png", "benz.png", "flok.png", "audi.png", "benz.png", "flok.png"]
and go to cellForItemAtIndexPath
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! MyCollectionCell
cell.layer.borderWidth = 0
cell.frame.size.width = screenSize.width
cell.frame.size.height = screenSize.height
// set cell size become fullscreen
cell.imgTest.image = UIImage(named: imageName[indexPath.row])
cell.imgTest.frame = CGRect(origin: CGPoint(x: 0, y: 0), size:cell.imgTest.image!.size)
//call my dummy image to cell
cell.scrollCell.addSubview(cell.imgTest)
cell.scrollCell.contentSize = cell.imgTest.image!.size
let scaleHeight = cell.scrollCell.frame.size.height / cell.scrollCell.contentSize.height
let scaleWidth = cell.scrollCell.frame.size.width / cell.scrollCell.contentSize.width
let minScale = min(scaleWidth, scaleHeight)
cell.scrollCell.minimumZoomScale = minScale
cell.scrollCell.maximumZoomScale = 1.0
cell.scrollCell.zoomScale = minScale
var doubleTapRecognizer = UITapGestureRecognizer(target: self, action: "scrollviewDoubleTapped")
doubleTapRecognizer.numberOfTapsRequired = 2
doubleTapRecognizer.numberOfTapsRequired = 1
cell.scrollCell.addGestureRecognizer(doubleTapRecognizer)
I run this project and the problem is
scroll size don't equal my image size but over
my image can't zoom (I already check "user interaction enabled")
I try using pinch gesture to solve it but I don't know how to set minimumzoomscale to it and the images can't scroll when zoom in
By this code I try using image from json with SDWebImage I change code in cellForItemAtIndexPath from call dummy image to this
cell.imgTest.sd_setImageWithURL(NSURL(string: dataArray[indexPath.row]), placeholderImage: UIImage(named: "loading.png"))
but this way Thread 1 : EXC_BAD_INSTRUCTION (code=EXC_1386_INVOP,subcode=0x0)
Where I go from here can anyone guide me in swift please
instead of a collection view use a scrollview, much easier, and more flexible. Check out this link very good tutorial.. You can merge the scrolled page and scroll zoom. UIScrollView Tutorial: Getting Started