Display multiple images on scrollview by using DKImagePickerController - ios

I would like to display multiple images on scrollview when user selected images with DKImagePickerController github.
Here is my code but images don't appear. Anyone can tell what's wrong?
Thank you in advance!
var picker = DKImagePickerController()
var imagesArray = [Any]()
#IBAction func pickPhoto(_ sender: Any) {
picker.maxSelectableCount = 10
picker.showsCancelButton = true
picker.allowsLandscape = false
picker.assetType = .allPhotos
self.present(picker, animated: true)
picker.didSelectAssets = { (assets: [DKAsset]) in
self.imagesArray.append(assets)
for i in 0..<self.imagesArray.count {
let imageView = UIImageView()
imageView.image = self.imagesArray[i] as? UIImage
imageView.contentMode = .scaleAspectFit
let xposition = self.view.frame.width * CGFloat(i)
imageView.frame = CGRect(x: xposition, y: 330, width: self.scrollView.frame.width, height: 170)
self.scrollView.contentSize.width = self.scrollView.frame.width * CGFloat(i * 1)
self.scrollView.addSubview(imageView)
}
}
}

Instead of displaying images to scrollView, you can add that images in array and reload the collectionView/TableView..
as I did it here in collectionView
func showImagePicker() {
let pickerController = DKImagePickerController()
self.previewView?.isHidden = false
pickerController.assetType = .allPhotos
pickerController.defaultAssetGroup = .smartAlbumUserLibrary
pickerController.didSelectAssets = { (assets: [DKAsset]) in
if assets.count>0
{
for var i in 0 ... assets.count-1 {
assets[i].fetchOriginalImage(true, completeBlock: { (image, info) in
self.abc.append(image)
})
}
}
self.previewView?.reloadData()
}
self.present(pickerController, animated: true) {}
}
Here abc :[UIImage] and previewView? : UICollectionView
and in collection delegate methods:
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return self.abc.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
var cell: UICollectionViewCell?
var imageView: UIImageView?
cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CellImage", for: indexPath)
imageView = cell?.contentView.viewWithTag(1) as? UIImageView
if let cell = cell, let imageView = imageView
{
let tag = indexPath.row + 1
cell.tag = tag
imageView.image = self.abc[indexPath.row]
}
return cell!
}

Related

Scrollview not scrolling in right

I have a scroll vie and i want to display the images selected by user in horizontal scroll manner. The following is my code. but, I am unable to achieve that. please guide me.
var xPosition: CGFloat = 0
var scrollViewContentWidth: CGFloat = 398
func handlePickedImage(image: UIImage){
let imageView = UIImageView(image: image)
imageView.frame = CGRect(x: 0, y: 0, width: 398, height: 188)
imageView.contentMode = UIView.ContentMode.scaleAspectFit
imageView.frame.origin.x = xPosition
imageView.frame.origin.y = 10
let spacer: CGFloat = 10
xPosition = 398 + spacer
scrollViewContentWidth = scrollViewContentWidth + spacer
imageScrollView.contentSize = CGSize(width: scrollViewContentWidth, height: 188)
imageScrollView.addSubview(imageView)
}
I have created just that with this code, it also has pagination implemented in it:
import UIKit
class ImagePagerViewController: UIViewController {
#IBOutlet weak var collectionView: UICollectionView!
var data: [FoodPostImageObject] = []
var userId: Int?
var indexPath: IndexPath?
var page: Int = 1
var alreadyFetchingData = false
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
collectionView.dataSource = self
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: self.view.frame.width, height: self.view.frame.height)
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
layout.scrollDirection = .horizontal
collectionView.collectionViewLayout = layout
if userId != nil {
getUserImages()
}
}
override func viewDidLayoutSubviews() {
guard self.indexPath != nil else {return}
self.collectionView.scrollToItem(at: self.indexPath!, at: .right, animated: false)
}
}
extension ImagePagerViewController: UICollectionViewDataSource, UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImagePagerCell", for: indexPath) as! ImagePagerCollectionViewCell
cell.image.loadImageUsingUrlString(urlString: data[indexPath.row].food_photo)
return cell
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return data.count
}
}
extension ImagePagerViewController {
func fetchMoreData(){
if !alreadyFetchingData {
if userId != nil {
getUserImages()
}
}
}
func getUserImages(){
guard let userId = self.userId else {return}
alreadyFetchingData = true
Server.get("/user_images/\(userId)/\(page)/"){ data, response, error in
self.alreadyFetchingData = false
guard let data = data else {return}
do {
self.data.append(contentsOf: try JSONDecoder().decode([FoodPostImageObject].self, from: data))
DispatchQueue.main.async {
self.collectionView.reloadData()
self.collectionView.scrollToItem(at: self.indexPath!, at: .right, animated: false)
self.page += 1
}
} catch {}
}
}
}
and this UICollectionViewCell:
import UIKit
class ImagePagerCollectionViewCell: UICollectionViewCell {
#IBOutlet weak var image: CellImageView!
}
In the storyboard I just have a collectionView and ImagePagerCollectionViewCell inside.
Hope this helps

How to set fix ImageView size inside TableViewCell programmatically?

I have this issue wherein I need to fix the size on an image inside a tableviewcell. The image below shows that the image size in not uniform.
Here are the codes I used.
if noteImageIsAvailable == true {
if let imageData = assignedNotePhoto?.photoData {
if let image = Utilities.resizePictureImage(UIImage(data: imageData as Data)) {
//added fix
cell.imageView?.frame.size = CGSize(width: 36, height: 24)
cell.imageView?.clipsToBounds = true
//-----
cell.imageView?.contentMode = .scaleAspectFill
cell.imageView?.image = image
}
}
}
I read an answer here in stackoverflow. It says I need to add clipToBounds but unfortunately it doesn't work. Please help me solve this issue. Thank you
TableView Code
extension SettingNoteViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Menu.SettingNote.items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "reuseIdentifier")
let keyPass = KeyHelper.NoteSetting.info[indexPath.row]
let assignedNotePhoto = self.getNotePhoto(key: keyPass.key)
let assignedNoteTextData = self.getNoteTextData(key: keyPass.key)?.value
cell.contentView.backgroundColor = .black
cell.textLabel?.textColor = .white
cell.detailTextLabel?.textColor = .white
cell.detailTextLabel?.numberOfLines = 0
let noteImageIsAvailable = assignedNotePhoto?.photoData != nil
if noteImageIsAvailable == true {
if let imageData = assignedNotePhoto?.photoData {
if let image = Utilities.resizePictureImage(UIImage(data: imageData as Data)) {
//added fix
cell.imageView?.translatesAutoresizingMaskIntoConstraints = false
cell.imageView?.frame.size = CGSize(width: 36, height: 24)
cell.imageView?.clipsToBounds = true
//-----
cell.imageView?.contentMode = UIView.ContentMode.scaleAspectFit
cell.imageView?.image = image
}
}
}
cell.textLabel?.text = Menu.SettingNote.items[indexPath.row].value
cell.detailTextLabel?.text = assignedNoteTextData ?? "noteSettingSubTitle".localized
return cell
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.destination is InputMemoViewController {
let vc = segue.destination as! InputMemoViewController
vc.infoNoteKey = self.infoNoteKeyToPass
vc.infoLabelText = self.infoLabelToPass
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.infoNoteKeyToPass = KeyHelper.NoteSetting.info[indexPath.row].key
self.infoLabelToPass = KeyHelper.NoteSetting.info[indexPath.row].label
self.performSegue(withIdentifier: "showInputMemo", sender: self)
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 80
}
}
The image below was the output when I applied #Kishan Bhatiya solution.
The first and second image is a landscape photo and the third image is in portrait
When you add cell.imageView?.translatesAutoresizingMaskIntoConstraints = false then frame has no effect, so try to use any one
let marginguide = contentView.layoutMarginsGuide
//imageView auto layout constraints
cell.imageView?.translatesAutoresizingMaskIntoConstraints = false
let marginguide = cell.contentView.layoutMarginsGuide
cell.imageView?.topAnchor.constraint(equalTo: marginguide.topAnchor).isActive = true
cell.imageView?.leadingAnchor.constraint(equalTo: marginguide.leadingAnchor).isActive = true
cell.imageView?.heightAnchor.constraint(equalToConstant: 40).isActive = true
cell.imageView?.widthAnchor.constraint(equalToConstant: 40).isActive = true
cell.imageView?.contentMode = .scaleAspectFill
cell.imageView?.layer.cornerRadius = 20 //half of your width or height
And it's better to set constraints in UITableViewCell
you know your imageview size. So you can resize your UIImage to imageView size.
extension UIImage{
func resizeImageWithHeight(newW: CGFloat, newH: CGFloat) -> UIImage? {
UIGraphicsBeginImageContext(CGSize(width: newW, height: newH))
self.draw(in: CGRect(x: 0, y: 0, width: newW, height: newH))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
}
use like that
let img = originalImage.resizeImageWithHeight(newW: 40, newH: 40)
cell.imageView?.image = img
Here, 40 40 is my imageview size
I have the same problem, scaleAspectFit is solved for me. you can try it
cell.imageView.contentMode = UIViewContentMode.scaleAspectFit

Gif when used as pagination loader, sometimes not displayed in image view

I am using collection view with pagination to show more data. At end of collection view I show an image view with gif file until data loads and then hide the image view. But sometimes gif doesn't load in the image view.
Please help and thanks in advance !!
I have tried changing libraries - Kingfisher, SDWebImage, ImageIO, UIImage+Gif etc. but it didn't help.
Also tried running on main thread.
class HorizontalScrollDealCollectionView: UICollectionView {
private var indicator:UIImageView!
private var offset:CGFloat = 0
private let loaderGif = UIImage.gif(name: "831")
override func awakeFromNib() {
super.awakeFromNib()
let frame = CGRect(x: 20, y: self.frame.height/2-15, width: 30, height: 30)
indicator = UIImageView(frame: frame)
indicator.image = loaderGif
indicator.backgroundColor = .blue
self.addSubview(indicator)
indicator.isHidden = true
}
override func layoutSubviews() {
super.layoutSubviews()
self.adjustIndicator()
}
func loadGifAnimatedIndicator() {
indicator.isHidden = true
indicator.image = loaderGif
}
private func adjustIndicator() {
indicator.frame.origin.x = self.contentSize.width + (offset/2)
let view = self.visibleCells.first
if let scrollViewAdjuster = view as? InfiniteScrollOffsetAdjuster {
indicator.frame.origin.y = scrollViewAdjuster.refralFrameForProgressView.height / 2 - 15
}
else {
indicator.frame.origin.y = self.contentSize.height / 2 - 15;
}
}
func showIndicator() {
if indicator.isHidden == false { return }
indicator.isHidden = false
indicator.image = loaderGif
indicator.startAnimating()
UIView.animate(withDuration: 0.2) {
self.contentInset.right = self.offset + 40
}
}
func hideIndicator() {
if indicator.isHidden { return }
self.indicator.isHidden = true
}
func resetContentInset(animate:Bool = true) {
UIView.setAnimationsEnabled(animate)
UIView.animate(withDuration: 0.1, animations: {
self.contentInset.right = 0
}) { (success) in
if !animate {
UIView.setAnimationsEnabled(true)
}
}
}
}
In ViewController
//Table View Delegate
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
guard let homeTableViewCell = cell as? HorizontalScrollHomeTableViewCell else {
return
}
homeTableViewCell.collectionView.loadGifAnimatedIndicator()
homeTableViewCell.collectionView.reloadData()
}
//Collection View Delegate
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
let horizontalCollView = collectionView as! HorizontalScrollDealCollectionView
let dataIndex = horizontalCollView.tableViewCellIndex!
let data = items[dataIndex.row]
if (indexPath.item == data.products.count - 1) && data.moreAvailable {
horizontalCollView.showIndicator()
data.loadMore(completion: {
(success) in
horizontalCollView.hideIndicator()
if success {horizontalCollView.reloadData()}
})
}
}
Screenshot 1
****Screenshot 2**
Changing
private let loaderGif = UIImage.gif(name: "831")
to
private var loaderGif: UIImage {
return UIImage.gif(name: "831")
}
solves the issue but tableview scrolling becomes laggy/jittering.
Also did this asynchronously using DispatchQueue but didn't helped. Still scrolling hangs.
func loadGifAnimatedIndicator() {
indicator.isHidden = true
DispatchQueue.main.async {
self.indicator.image = self.loaderGif
}
}

UICollectionView Cell Custom FlowLayout Breaks When New Post is Added on Top

Description:
I have been working on an app which displays images and caption in a CollectionView. I have made a custom Cell and CustomFlowLayout for the cell where the width of the cell, image and caption is equal to width of screen and height will change according to aspect ratio of the image height and height needed for the caption. The images which are displayed are stored on FirebaseStorage and I have also saved imagewidth and imageheight in firebaseDatabase. I Use SD_Web images to load and cache images. When the app loads for the first time the layout works perfectly fine as expected. The cells are arranged according to image height and caption height , with images being in aspect ratio.
The main problem occurs when a new post is done. I insert new post on the top of collectionview, and when the post is received the layout breaks, images becomes messed up, the caption goes on top image, lot of white space between image or caption. when I terminate the app from background and run it again , this time the layout is perfectly fine with new post present. I have to terminate app after everyone post to make the layout work.
What I feel the problem is, when I post the image. The new post is added on the top cell and the item on top cell pushed below without having the old height. how can I take this problem. I tried searching a lot but still of no use.
PS:
Using Autolayout for cell in IB.
FactsFeverLayout Class
import UIKit
protocol FactsFeverLayoutDelegate: class {
func collectionView(CollectionView: UICollectionView, heightForThePhotoAt indexPath: IndexPath, with width: CGFloat) -> CGFloat
func collectionView(CollectionView: UICollectionView, heightForCaptionAt indexPath: IndexPath, with width: CGFloat) -> CGFloat
}
class FactsFeverLayout: UICollectionViewLayout {
var cellPadding : CGFloat = 5.0
var delegate: FactsFeverLayoutDelegate?
private var contentHeight : CGFloat = 0.0
private var contentWidth : CGFloat {
let insets = collectionView!.contentInset
return (collectionView!.bounds.width - insets.left + insets.right)
}
private var attributeCache = [FactsFeverLayoutAttributes]()
override func prepare() {
if attributeCache.isEmpty {
let containerWidth = contentWidth
var xOffset : CGFloat = 0
var yOffset : CGFloat = 0
for item in 0 ..< collectionView!.numberOfItems(inSection: 0) {
let indexPath = IndexPath(item: item, section: 0)
let width = containerWidth - cellPadding * 2
let photoHeight:CGFloat = (delegate?.collectionView(CollectionView: collectionView!, heightForThePhotoAt: indexPath, with: width))!
let captionHeight: CGFloat = (delegate?.collectionView(CollectionView: collectionView!, heightForCaptionAt: indexPath, with: width))!
let height: CGFloat = cellPadding + photoHeight + captionHeight + cellPadding
let frame = CGRect(x: xOffset, y: yOffset, width: containerWidth, height: height)
let insetFrame = frame.insetBy(dx: cellPadding, dy: cellPadding)
// Create CEll Layout Atributes
let attributes = FactsFeverLayoutAttributes(forCellWith: indexPath)
attributes.photoHeight = photoHeight
attributes.frame = insetFrame
attributeCache.append(attributes)
// Update The Colunm any Y axis
contentHeight = max(contentHeight, frame.maxY)
yOffset = yOffset + height
}
}
}
override var collectionViewContentSize: CGSize{
return CGSize(width: contentWidth, height: contentHeight)
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var layoutAttributes = [UICollectionViewLayoutAttributes]()
for attributes in attributeCache {
if attributes.frame.intersects(rect){
layoutAttributes.append(attributes)
}
}
return layoutAttributes
}
}
// UICollectionView FlowLayout
// Abstract
class FactsFeverLayoutAttributes: UICollectionViewLayoutAttributes {
var photoHeight : CGFloat = 0.0
override func copy(with zone: NSZone? = nil) -> Any {
let copy = super.copy(with: zone) as! FactsFeverLayoutAttributes
copy.photoHeight = photoHeight
return copy
}
override func isEqual(_ object: Any?) -> Bool {
if let attributes = object as? FactsFeverLayoutAttributes {
if attributes.photoHeight == photoHeight {
super.isEqual(object)
}
}
return false
}
}
CollectionViewCell Class
class NewCellCollectionViewCell: UICollectionViewCell {
var facts: Facts!
var currentUser = Auth.auth().currentUser?.uid
// IBOutlets
#IBOutlet weak var imageView: UIImageView!
#IBOutlet weak var imageHeightConstraint: NSLayoutConstraint!
#IBOutlet weak var likeLable: UILabel!
#IBOutlet weak var likeButton: UIButton!
#IBOutlet weak var infoButton: UIButton!
#IBOutlet weak var buttonView: UIView!
#IBOutlet weak var captionTextView: UITextView!
override func awakeFromNib() {
super.awakeFromNib()
likeButton.setImage(UIImage(named: "noLike"), for: .normal)
likeButton.setImage(UIImage(named: "like"), for: .selected)
setupLayout()
}
func configureCell(fact: Facts){
facts = fact
imageView.sd_setImage(with: URL(string: fact.factsLink))
likeLable.text = String(fact.factsLikes.count)
captionTextView.text = fact.captionText
let factsRef = Database.database().reference().child("Facts").child(facts.factsId).child("likes")
factsRef.observeSingleEvent(of: .value) { (snapshot) in
if fact.factsLikes.contains(self.currentUser!){
self.likeButton.isSelected = true
} else {
self.likeButton.isSelected = false
}
}
}
override func apply(_ layoutAttributes: UICollectionViewLayoutAttributes) {
super.apply(layoutAttributes)
if let attributes = layoutAttributes as? FactsFeverLayoutAttributes {
imageHeightConstraint.constant = attributes.photoHeight
}
}
}
ViewController Class
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
//MARK: Outlets
#IBOutlet weak var uploadButtonOutlet: UIBarButtonItem!
#IBOutlet weak var collectionView: UICollectionView!
//MARK:- Properties
var images: [UIImage] = []
var factsArray:[Facts] = [Facts]()
var likeUsers:[String] = []
let currentUser = Auth.auth().currentUser?.uid
private let refreshControl = UIRefreshControl()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
if #available(iOS 10.0, *) {
collectionView.refreshControl = refreshControl
} else {
collectionView.addSubview(refreshControl)
}
refreshControl.addTarget(self, action: #selector(refreshView), for: .valueChanged)
refreshControl.tintColor = UIColor.white
if let layout = collectionView?.collectionViewLayout as? FactsFeverLayout {
layout.delegate = self
}
collectionView.backgroundColor = UIColor.black
observeFactsFromFirebase()
}
#objc func refreshView(){
observeFactsFromFirebase()
}
//MARK:- Upload Facts
#IBAction func uploadButtonPressed(_ sender: Any) {
self.selectPhoto()
(deleted the function of selectPhoto but it works, UIImagePicker is used)
}
private func uploadImageToFirebaseStorage(image: UIImage, completion: #escaping (_ imageUrl: String) -> ()){
let imageName = NSUUID().uuidString + ".jpg"
let ref = Storage.storage().reference().child("message_images").child(imageName)
if let uploadData = image.jpegData(compressionQuality: 0.2){
ref.putData(uploadData, metadata: nil, completion: { (metadata, error) in
if error != nil {
print(" Failed to upload Image", error)
}
ref.downloadURL(completion: { (url, err) in
if let err = err {
print("Unable to upload image into storage due to \(err)")
}
let messageImageURL = url?.absoluteString
completion(messageImageURL!)
})
})
}
}
func addToDatabase(imageUrl:String, caption: String, image: UIImage){
let Id = NSUUID().uuidString
likeUsers.append(currentUser!)
let timeStamp = NSNumber(value: Int(NSDate().timeIntervalSince1970))
let factsDB = Database.database().reference().child("Facts")
let factsDictionary = ["factsLink": imageUrl, "likes": likeUsers, "factsId": Id, "timeStamp": timeStamp, "captionText": caption, "imageWidth": image.size.width, "imageHeight": image.size.height] as [String : Any]
factsDB.child(Id).setValue(factsDictionary){
(error, reference) in
if error != nil {
print(error)
ProgressHUD.showError("Image Upload Failed")
self.uploadButtonOutlet.isEnabled = true
return
} else{
print("Message Saved In DB")
ProgressHUD.showSuccess("image Uploded Successfully")
self.uploadButtonOutlet.isEnabled = true
self.observeFactsFromFirebase()
}
}
}
var imageUrl: [String] = []
func observeFactsFromFirebase(){
let factsDB = Database.database().reference().child("Facts").queryOrdered(byChild: "timeStamp")
factsDB.observe(.value){ (snapshot) in
print("Observer Data snapshot \(snapshot.value)")
self.factsArray = []
self.imageUrl = []
self.likeUsers = []
if let snapshot = snapshot.children.allObjects as? [DataSnapshot] {
for snap in snapshot {
if let postDictionary = snap.value as? Dictionary<String, AnyObject> {
let id = snap.key
let facts = Facts(dictionary: postDictionary)
self.factsArray.insert(facts, at: 0)
self.imageUrl.insert(facts.factsLink, at: 0)
}
}
}
self.collectionView.reloadData()
self.refreshControl.endRefreshing()
}
collectionView.reloadData()
}
// Download Image From Database
//-> Here I download image from firebase and store it locally and append it to images array (Deleted the code to remove unwanted clutter)
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
//MARK: Data Source
extension ViewController: UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return factsArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let facts = factsArray[indexPath.row]
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "newCellTrial", for: indexPath) as? NewCellCollectionViewCell
cell?.configureCell(fact: facts)
cell?.infoButton.addTarget(self, action: #selector(reportButtonPressed), for: .touchUpInside)
return cell!
}
}
extension ViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
collectionView.deselectItem(at: indexPath, animated: true)
let photos = IDMPhoto.photos(withURLs: imageUrl)
let browser = IDMPhotoBrowser(photos: photos)
browser?.setInitialPageIndex(UInt(indexPath.row))
self.present(browser!, animated: true, completion: nil)
}
}
extension ViewController: FactsFeverLayoutDelegate {
func collectionView(CollectionView: UICollectionView, heightForThePhotoAt indexPath: IndexPath, with width: CGFloat) -> CGFloat {
let facts = factsArray[indexPath.item]
let imageSize = CGSize(width: CGFloat(facts.imageWidht), height: CGFloat(facts.imageHeight))
let boundingRect = CGRect(x: 0, y: 0, width: width, height: CGFloat(MAXFLOAT))
let rect = AVMakeRect(aspectRatio: imageSize, insideRect: boundingRect)
return rect.size.height
}
func collectionView(CollectionView: UICollectionView, heightForCaptionAt indexPath: IndexPath, with width: CGFloat) -> CGFloat {
let fact = factsArray[indexPath.item]
let topPadding = CGFloat(8)
let bottomPadding = CGFloat(8)
let captionFont = UIFont.systemFont(ofSize: 15)
let viewHeight = CGFloat(40) //-> There is view below caption which holds like button and info button its height is constant (40)
let captionHeight = self.height(for: fact.captionText, with: captionFont, width: width)
let height = topPadding + captionHeight + topPadding + viewHeight + bottomPadding + topPadding + 10
return height
}
func height(for text: String, with font: UIFont, width: CGFloat) -> CGFloat {
let nsstring = NSString(string: text)
let maxHeight = CGFloat(1000)
let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
let textAttributes = [NSAttributedString.Key.font: font]
let boundingRect = nsstring.boundingRect(with: CGSize(width: width, height: maxHeight), options: options, attributes: textAttributes, context: nil)
return ceil(boundingRect.height)
}
}
as you have used attributeCache, layoutAttribute of First Cell is Already Stored in cache.when you add images at first place and reload your collectionView , old Attribute for First cell will be retired from Cache and applying to your collectionView layout.
so you have to remove Element From Cache before reloading
override func prepare() {
attributeCache.RemoveAll()
if attributeCache.isEmpty {
let containerWidth = contentWidth
var xOffset : CGFloat = 0
var yOffset : CGFloat = 0
for item in 0 ..< collectionView!.numberOfItems(inSection: 0) {
let indexPath = IndexPath(item: item, section: 0)
let width = containerWidth - cellPadding * 2
let photoHeight:CGFloat = (delegate?.collectionView(CollectionView: collectionView!, heightForThePhotoAt: indexPath, with: width))!
let captionHeight: CGFloat = (delegate?.collectionView(CollectionView: collectionView!, heightForCaptionAt: indexPath, with: width))!
let height: CGFloat = cellPadding + photoHeight + captionHeight + cellPadding
let frame = CGRect(x: xOffset, y: yOffset, width: containerWidth, height: height)
let insetFrame = frame.insetBy(dx: cellPadding, dy: cellPadding)
// Create CEll Layout Atributes
let attributes = FactsFeverLayoutAttributes(forCellWith: indexPath)
attributes.photoHeight = photoHeight
attributes.frame = insetFrame
attributeCache.append(attributes)
// Update The Colunm any Y axis
contentHeight = max(contentHeight, frame.maxY)
yOffset = yOffset + height
}
}
}

iOS: in Swift3, in my collectionView, when I scroll downstair, the collectionView comes automatically at the top. How to stop it?

I would like my collectionView to stop in the cell. The problem is that when I scroll downstair, if I release it, it comes automatically at the first position...
I tried with collection.alwaysBounceVertical = true without success...
Here is my code:
override func viewDidLoad() {
super.viewDidLoad()
let layout = OrganiserLayout()
let frameCollection = CGRect(x: self.view.frame.origin.x, y: self.view.frame.origin.y, width: self.view.frame.width, height: self.view.frame.height + 1000)
let collection = UICollectionView(frame: frameCollection, collectionViewLayout: layout)
collection.delegate = self
collection.dataSource = self
collection.backgroundColor = UIColor.white
collection.register(OrganiserCollectionViewCell.self, forCellWithReuseIdentifier: "cell")
self.view.addSubview(collection)
collection.alwaysBounceVertical = true
collection.alwaysBounceHorizontal = true
collection.bounces = true
collection.isPagingEnabled = false
collection.isScrollEnabled = true
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 15
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
switch section {
case 0:
return 40
}
}
class OrganiserLayout:UICollectionViewLayout {
let cellWidth:CGFloat = 100
var attrDict = Dictionary<IndexPath,UICollectionViewLayoutAttributes>()
var contentSize = CGSize.zero
override var collectionViewContentSize : CGSize {
return self.contentSize
}
override func prepare() {
// Generate the attributes for each cell based on the size of the collection view and our chosen cell width
if let cv = collectionView {
let collectionViewHeight = cv.frame.height
let numberOfSections = cv.numberOfSections
self.contentSize = cv.frame.size
self.contentSize.width = cellWidth*CGFloat(numberOfSections)
for section in 0...numberOfSections-1 {
let numberOfItemsInSection = cv.numberOfItems(inSection: section)
let itemHeight = collectionViewHeight/CGFloat(numberOfItemsInSection)
let itemXPos = cellWidth*CGFloat(section)
for item in 0...numberOfItemsInSection-1 {
let indexPath = IndexPath(item: item, section: section)
let itemYPos = itemHeight*CGFloat(item)
let attr = UICollectionViewLayoutAttributes(forCellWith: indexPath)
attr.frame = CGRect(x: itemXPos, y: itemYPos, width: cellWidth, height: itemHeight)
attrDict[indexPath] = attr
}
}
}
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
// Here we return the layout attributes for cells in the current rectangle
var attributesInRect = [UICollectionViewLayoutAttributes]()
for cellAttributes in attrDict.values {
if rect.intersects(cellAttributes.frame) {
attributesInRect.append(cellAttributes)
}
}
return attributesInRect
}
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
// Here we return one attribute object for the specified indexPath
return attrDict[indexPath]!
}
}
class OrganiserCollectionViewCell:UICollectionViewCell {
var label:UILabel!
var seperator:UIView!
override init(frame: CGRect) {
super.init(frame: frame)
label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(label)
seperator = UIView()
seperator.backgroundColor = UIColor.black
seperator.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(seperator)
let views:[String:UIView] = [
"label":label,
"sep":seperator
]
let cons = [
"V:|-20-[label]",
"V:[sep(1)]|",
"H:|[label]|",
"H:|[sep]|"
]
for con in cons {
self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: con, options: [], metrics: nil, views: views))
}
}
I need that because I need the user stops on the cell, and click on it. With that problem, he cannot click on the cells that are downstairs.
Thanks in advance.
Set some height for contentSize like below :
self.contentSize.height = CGFloat(2750)
In your code :
class OrganiserLayout:UICollectionViewLayout {
override func prepare() {
// Generate the attributes for each cell based on the size of the collection view and our chosen cell width
if let cv = collectionView {
let collectionViewHeight = cv.frame.height
let numberOfSections = cv.numberOfSections
self.contentSize = cv.frame.size
self.contentSize.width = cellWidth*CGFloat(numberOfSections)
self.contentSize.height = CGFloat(2750) // I added this line
for section in 0...numberOfSections-1 {
let numberOfItemsInSection = cv.numberOfItems(inSection: section)
let itemHeight = collectionViewHeight/CGFloat(numberOfItemsInSection)
let itemXPos = cellWidth*CGFloat(section)
for item in 0...numberOfItemsInSection-1 {
let indexPath = IndexPath(item: item, section: section)
let itemYPos = itemHeight*CGFloat(item)
let attr = UICollectionViewLayoutAttributes(forCellWith: indexPath)
attr.frame = CGRect(x: itemXPos, y: itemYPos, width: cellWidth, height: itemHeight)
attrDict[indexPath] = attr
}
}
}
}
}

Resources