-2

i m totally confuse what should i do for increase tableview cell hight at runtime when user enter some text in UITextview and i give constrain to UItextView that left , right , bottom , and upside spacing 5px. that i show in my screen and i don't use any Custom tableviewcell class . i want to perform this task in single controller. i just use XCode 7.3 and my swift version 2.0

 @IBOutlet var tedxtviewtableview: UITableView!
  var record : NSArray = NSArray()
  var  hight: CGFloat = 0.0
  var newtextstring : NSString = NSString()

my static array .

 record = ["I have a UITextView in a custom UITableViewCell. The textview delegate is assigned in the tableviewcell custom class." ,"Textview scrolling is disabled. Text loads into each textview and is multiline. But the text is always clipped because the cell height doesn't change.","I have the following in viewDidLoad of the tableview controller:"," have a UITextView in a custom UITableViewCell. The textview delegate is assigned in the tableviewcell custom class.","Textview scrolling is disabled. Text loads into each textview and is multiline. But the text is always clipped because the cell height doesn't change.","I have the following in viewDidLoad of the tableview controller:","i just give you one link at put place i use label and you can now use your textview and give same constrain that i give in that link and try it so your problem will be solve","I have the following in viewDidLoad of the tableview controller:"];

// tableview delegates method

 func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return record.count
 }

 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
       let cell = tableView.dequeueReusableCellWithIdentifier("Textviewcell", forIndexPath: indexPath)
       let textview: UITextView = (cell.viewWithTag(5) as! UITextView)
       textview.scrollEnabled = false
       textview.text = record.objectAtIndex(indexPath.row) as? String
       Textchange = false
       return cell

}
func textViewDidChange(textView: UITextView , Nsindex : NSIndexPath) {
        newtextstring = textView.text
        self.tedxtviewtableview.beginUpdates()

        // This will cause an animated update of
        Textchange = true
        self.tableView(self.tedxtviewtableview, heightForRowAtIndexPath: Nsindex)
        self.tedxtviewtableview.endUpdates()

}

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        // 7.1>
        if Textchange == true {
            hight = self.findHeightForText(newtextstring as String, havingWidth: self.view.frame.size.width - 10, andFont: UIFont.systemFontOfSize(14.0)).height
            return 44 + hight
        }else{
            hight = self.findHeightForText(self.record.objectAtIndex(indexPath.row) as! String, havingWidth: self.view.frame.size.width - 10, andFont: UIFont.systemFontOfSize(14.0)).height
            return 44 + hight
        }
   }

 func findHeightForText(text: String, havingWidth widthValue: CGFloat, andFont font: UIFont) -> CGSize {

    var size = CGSizeZero
    if text.isEmpty == false {
    let frame = text.boundingRectWithSize(CGSizeMake(widthValue, CGFloat.max), options: .UsesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)
        size = CGSizeMake(frame.size.width, ceil(frame.size.height))
     }
     return size
    }

Himanshu Moradiya
  • 4,769
  • 4
  • 25
  • 49
  • If i am not wrong you are looking for this http://stackoverflow.com/questions/39868532/can-i-change-height-of-uitableviewcell-real-time/39870884#39870884 – Maniganda saravanan Oct 19 '16 at 07:14
  • See the second part of my answer: http://stackoverflow.com/questions/40071611/how-can-i-modify-the-heightforrowatindexpath-so-that-it-adjust-height-to-the-tex/40072101#40072101 – Rikh Oct 19 '16 at 07:14
  • Just delegate your textview on your tableview controller and call tableview `beginUpdate` and `endUpdate` on textView's `textDidChange` and it will recalculate your cell height, if you support ios8+ then use `UITableViewAutomaticDimension` for cell height is better – Tj3n Oct 19 '16 at 07:14
  • @Manigandasaravanan i already see that your answer but its not help me so i upload my question – Himanshu Moradiya Oct 19 '16 at 07:16
  • I think it should be enough to: (1) Set all four constraints between text view and cell's content view (you've got this covered), and (2) **Disable** textview scrolling. – Nicolas Miari Oct 19 '16 at 07:18
  • @Rikh i dont want to use UIlabel and ya in that case if i disable textview.scrollEnabled = false then its not show me that i enter text . – Himanshu Moradiya Oct 19 '16 at 07:19
  • @NicolasMiari i just updated my question see it – Himanshu Moradiya Oct 19 '16 at 07:22
  • @HimanshuMoradiya the second part of my answer in that post says to take a height constraint for the textView and increase it based on the string you obtain. Using this is a hint you can increment the size of the textView to be equal to the contentSize of the textView that you can get in one of the textViewDelegates. – Rikh Oct 19 '16 at 07:26
  • @Rikh it will give me error when i give constrain to greater then equal to my uitextview so you check it – Himanshu Moradiya Oct 19 '16 at 07:29
  • I never said to add a greater than or equal constraint. You need to add a simple height constraint that initially can be anything as you are going to resize it in your code later anyways. Use the default value that pops up when adding the height constraint. – Rikh Oct 19 '16 at 07:32
  • @Rikh not able create outlet NSLayoutConstraint of textview hight in the tableview i try something else to solve my problem and thank you for your kind attention – Himanshu Moradiya Oct 19 '16 at 09:02

2 Answers2

1

Take a variable

 var indexPath1 : NSIndexPath = NSIndexPath()

Just change this thing in your code

func textViewDidChange(textView: UITextView){

        let textFieldRowCell = (textView.superview!.superview! as! UITableViewCell)
         indexPath1 = self.tedxtviewtableview.indexPathForCell(textFieldRowCell)! //self.tedxtviewtableview.indexPath(forCell: textFieldRowCell)!

        newtextstring = textView.text
       self.tedxtviewtableview.beginUpdates()

        // This will cause an animated update of
        //Textchange = true
        self.tableView(self.tedxtviewtableview, heightForRowAtIndexPath: indexPath1)
       self.tedxtviewtableview.endUpdates()

    }

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        // 7.1>
        if indexPath == indexPath1 {
              hight = self.findHeightForText(newtextstring as String, havingWidth: self.view.frame.size.width - 10, andFont: UIFont.systemFontOfSize(14.0)).height
            return 44 + hight
        }else{
            hight = self.findHeightForText(self.record.objectAtIndex(indexPath.row) as! String, havingWidth: self.view.frame.size.width - 10, andFont: UIFont.systemFontOfSize(14.0)).height
            return 44 + hight
        }
   }

Hope it will work

Jitendra Modi
  • 2,344
  • 12
  • 34
0
//
//  ViewController.swift
//  CapturePhotoApp
//
//  Created by CS23 on 09/08/17.
//  Copyright © 2017 cearsinfotech. All rights reserved.
//

import UIKit
import PinterestLayout
import Stripe
class ViewController: UIViewController ,UICollectionViewDelegate , UICollectionViewDataSource , PinterestLayoutDelegate , UIGestureRecognizerDelegate{

    @IBOutlet var MainView: UIView!

    @IBOutlet var LightHeaderView: UIView!
    @IBOutlet var LightHeaderWidth: NSLayoutConstraint!
    @IBOutlet var lblHeaderTitle: UILabel!
    var isAppfirst : Bool = false
    var isscrolling : Bool = true
    var Isopen : Bool = true
    var Globaltimer: Timer?

    @IBOutlet var TutorialView: UIView!
    var ismoredata : Bool = false
    var IsFinish = false
    var pageCount = 1
    var pageSize = 30
    var orderType : String = ""
    var lastcellindex : Int = 1

    var DownloadiMage : UIImageView = UIImageView()

    @IBOutlet var GotITWidth: NSLayoutConstraint!
    @IBOutlet var btnTutorialgotit: UIButton!
    @IBOutlet var ImageCollectionview: UICollectionView!
    var arr_img : NSMutableArray = NSMutableArray()
    var arr_responseObject : NSMutableArray = NSMutableArray()
    var swipeRight : UISwipeGestureRecognizer?
    var swipeleft : UISwipeGestureRecognizer?

    @IBAction func btn_got_it(_ sender: Any) {
        UserDefaults.standard.set(true, forKey: "isFirstView")
        UserDefaults.standard.synchronize()
        TutorialView.isHidden = true
        self.LightHeaderView.alpha = 1.0
        UIView.animate(withDuration: 5.0, animations: {
            self.LightHeaderView.alpha = 0.0
            self.view.layoutIfNeeded()

        })
    }
    var manager = AFHTTPSessionManager()


    //MARK:- view life cycle

    override func viewDidLoad() {
        super.viewDidLoad()

        if let isfirst = UserDefaults.standard.object(forKey: "isFirstView") as? Bool {
            isAppfirst = isfirst
            TutorialView.isHidden = true
            GIFProgressHUD .show(withGIFName: "loader", addedTo: self.view, animated: true)

        }
        else{
            TutorialView.isHidden = false
        }
        btnTutorialgotit.layer.cornerRadius = btnTutorialgotit.frame.size.height / 2
        btnTutorialgotit.clipsToBounds = true
        LightHeaderView.layer.cornerRadius = LightHeaderView.frame.size.height / 2
        LightHeaderView.clipsToBounds = true
        LightHeaderView.alpha = 0.0
        orderType = "New"
        lblHeaderTitle.text = orderType.uppercased()
        if UIDevice.current.userInterfaceIdiom == .pad{
            ImageCollectionview.scrollPointsPerSecond = 70.0
            LightHeaderWidth.constant = 300
            GotITWidth.constant = 286
        }else{
            if UIScreen.main.bounds.width == 375
            {
                 GotITWidth.constant = 230
                ImageCollectionview.scrollPointsPerSecond = 70.0
                LightHeaderWidth.constant = 180
            }
            else if UIScreen.main.bounds.width == 414
            {
                 GotITWidth.constant = 286
                ImageCollectionview.scrollPointsPerSecond = 90.0
                LightHeaderWidth.constant = 200
            }
            else{
               ImageCollectionview.scrollPointsPerSecond = 70.0
            }
        }

        let layout = PinterestLayout()
        ImageCollectionview.collectionViewLayout = layout
        layout.delegate = self
        layout.cellPadding = 3
        layout.numberOfColumns = 3

        self.callWebserviceAuthorize(pageindex: pageCount, Pagesize: pageSize)
        self.ImageCollectionview.addInfiniteScrolling {

            if !self.IsFinish{
                self.pageCount += 1
                self.callWebserviceAuthorize(pageindex: self.pageCount, Pagesize: self.pageSize)
            }

        }
        //pushProductView
        NotificationCenter.default.addObserver(self, selector: #selector(ViewController.methodOfReceivedNotification(notification:)), name: Notification.Name("pushProductViewNew"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(ViewController.openSearchView(notification:)), name: Notification.Name("openSearchView"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(ViewController.NewDataLoadNotification(notification:)), name: Notification.Name("RemoveGestureNewPhoto"), object: nil)

        if AppUtilities.sharedInstance.GetBoolForObserver(str: "NewPhoto") != "1"{

        }
        if AppUtilities.sharedInstance.isactivemode{
            // here open view image

            let imageInfo = JTSImageInfo()
            imageInfo.imageURL = URL(string: (AppUtilities.sharedInstance.ImagePrivewDict.object(forKey: "url") as? String)!)
            imageInfo.istrading = AppUtilities.sharedInstance.ImagePrivewDict.object(forKey: "Istrading") as! String
            imageInfo.title = AppUtilities.sharedInstance.ImagePrivewDict.object(forKey: "title") as? String
            imageInfo.altText = AppUtilities.sharedInstance.ImagePrivewDict.object(forKey: "altText") as? String
            imageInfo.thumbnail =  AppUtilities.sharedInstance.ImagePrivewDict.object(forKey: "Thumbnail") as? String
            let imageViewer = JTSImageViewController(imageInfo: imageInfo, arry: nil, index: 0, mode: .image, backgroundStyle: .blurred)
            print(imageInfo)
            imageViewer?.show(from: self, transition: .center)
            AppUtilities.sharedInstance.isactivemode = false

        }

    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
         setGestureInCollectionview()
        AppUtilities.lockOrientation(.all)
        UIApplication.shared.statusBarStyle = .default
        if Isopen == false{
            self.perform(#selector(self.startTimer), with: nil, afterDelay: 5.0)
        }

        if AppUtilities.sharedInstance.appDelegate.is_Landscape != UIDevice.current.orientation.isLandscape{
            self.ImageCollectionview.reloadData()

        }

        Isopen = true
    }



    override func viewWillDisappear(_ animated: Bool) {
        stopTimer()
        NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(startTimer), object: nil)
        Isopen = false
        //NotificationCenter.default.removeObserver(self, name: Notification.Name("RemoveGestureNewPhoto"), object: nil)
    }

    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)
        if Isopen == false{
            //  stopSamllTimer()
            self.ImageCollectionview .stopScrolling()
            self.ImageCollectionview.reloadData()
            return
        }else{
            // stopSamllTimer()
            if UIDevice.current.orientation.isLandscape {
                AppUtilities.sharedInstance.appDelegate.is_Landscape = true
                print("Landscape")
                self.ImageCollectionview.reloadData()

            } else {
                AppUtilities.sharedInstance.appDelegate.is_Landscape = false
                print("Portrait")
                self.ImageCollectionview.reloadData()
            }
            self.ImageCollectionview .stopScrolling()
        }
    }

    func NewDataLoadNotification(notification: Notification){

        if notification.userInfo != nil{
            self.setGestureInCollectionview()
        }else{
            ImageCollectionview.removeGestureRecognizer(swipeRight!)
            ImageCollectionview.removeGestureRecognizer(swipeleft!)
        }

    }

    func openSearchView(notification: Notification){
        self.stopTimer()

        let dict : NSDictionary = notification.userInfo! as NSDictionary
        print(dict)
        if Isswipe == true{
            self.dismissPopupViewControllerWithanimationType(MJPopupViewAnimationSlideLeftRight)
        }

        let view: ProductShippingViewController = (self.storyboard?.instantiateViewController(withIdentifier: "ProductShippingViewController"))! as! ProductShippingViewController
        view.newphotoasset = String(format: "%@", dict.value(forKey: "Url") as! NSString) as NSString
        view.ThumbnailURL = String(format: "%@", dict.value(forKey: "Thumbnail") as! NSURL) as NSString
        AppUtilities.lockOrientation(.portrait)
        self.navigationController?.pushViewController(view, animated: true)


//            let viewController: SearchViewController = (self.storyboard?.instantiateViewController(withIdentifier: "SearchViewController"))! as! SearchViewController
//            
//            let aObjNavi = UINavigationController(rootViewController: viewController)
//            aObjNavi.isNavigationBarHidden = true
//            present(aObjNavi, animated: false, completion: nil)

//            let viewController: TradingViewController = (self.storyboard?.instantiateViewController(withIdentifier: "TradingViewController"))! as! TradingViewController
//            
//            let aObjNavi = UINavigationController(rootViewController: viewController)
//            aObjNavi.isNavigationBarHidden = true
//            present(aObjNavi, animated: false, completion: nil)



    }

    //MARK:- Gesture Methods

    func setGestureInCollectionview(){
         swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(self.SwipeGesture))
        swipeRight?.direction = UISwipeGestureRecognizerDirection.right
        ImageCollectionview.addGestureRecognizer(swipeRight!)

         swipeleft = UISwipeGestureRecognizer(target: self, action: #selector(self.SwipeGesture))
        swipeleft?.direction = UISwipeGestureRecognizerDirection.left
        ImageCollectionview.addGestureRecognizer(swipeleft!)
    }

    func SwipeGesture(_ gesture: UIGestureRecognizer) {
        self.ImageCollectionview.stopScrolling()
        self.stopTimer()
      // self.dismiss(animated: false, completion: nil)
        if let swipeGesture = gesture as? UISwipeGestureRecognizer {

            switch swipeGesture.direction {
            case UISwipeGestureRecognizerDirection.right:
                print("Swiped right")
                Isswipe = true
                let viewController: TradingViewController = (self.storyboard?.instantiateViewController(withIdentifier: "TradingViewController"))! as! TradingViewController

                let aObjNavi = UINavigationController(rootViewController: viewController)
                aObjNavi.isNavigationBarHidden = true

                present(aObjNavi, animated: false, completion: {

                  //  AppUtilities.sharedInstance.GiveShadowToMainView(View: viewController.MainView!, offset: CGSize(width: 5.0, height: 5.0))
                     viewController.MainView.frame = CGRect(x: -viewController.view!.frame.size.width, y: 0, width: viewController.view!.frame.size.width, height: viewController.MainView.frame.size.height)
                    UIView.animate(withDuration: ViewChangeAnimationDuration, delay: 0.0, options: [.curveEaseOut], animations: {
                          viewController.view!.frame.origin = CGPoint(x: 0, y: 0)
                        self.view.layoutIfNeeded()

                    }, completion: { (finished: Bool) in

                        //AppUtilities.sharedInstance.RemoveShadows(View: viewController.MainView!)
                    })
                })
               // self.presentPopupViewController(aObjNavi, animationType: MJPopupViewAnimationSlideLeftRight)


            case UISwipeGestureRecognizerDirection.left:
                print("Swiped left")
                 //Searching
                Isswipe = true
                let viewController: SearchViewController = (self.storyboard?.instantiateViewController(withIdentifier: "SearchViewController"))! as! SearchViewController

                let aObjNavi = UINavigationController(rootViewController: viewController)
                aObjNavi.isNavigationBarHidden = true
                present(aObjNavi, animated: false, completion: {

                  // AppUtilities.sharedInstance.GiveShadowToMainView(View: viewController.view!, offset: CGSize(width: -5.0, height: 5.0))
                     viewController.view!.frame = CGRect(x: viewController.view!.frame.size.width, y: 0, width: viewController.view!.frame.size.width, height: viewController.view!.frame.size.height)
                    UIView.animate(withDuration: ViewChangeAnimationDuration, delay: 0.0, options: [.curveEaseIn], animations: {
                        viewController.view!.frame.origin = CGPoint(x: 0, y: 0)
                        self.view.layoutIfNeeded()

                    }, completion: { (finished: Bool) in

                       // AppUtilities.sharedInstance.RemoveShadows(View: viewController.view!)
                    })
                })

               //self.presentPopupViewController(aObjNavi, animationType: MJPopupViewAnimationSlideRightLeft)
            default:
                break
            }
        }
    }

    func methodOfReceivedNotification(notification: Notification){
        //Take Action on Notification
        print(notification.userInfo!)

        if Isswipe == true{
            self.dismissPopupViewControllerWithanimationType(MJPopupViewAnimationSlideLeftRight)
        }
        let dict : NSDictionary = notification.userInfo! as NSDictionary
       // let navi : UINavigationController = UINavigationController()
        let view: ProductShippingViewController = (self.storyboard?.instantiateViewController(withIdentifier: "ProductShippingViewController"))! as! ProductShippingViewController
        view.newphotoasset = String(format: "%@", dict.value(forKey: "Url") as! NSString) as NSString
        view.ThumbnailURL = String(format: "%@", dict.value(forKey: "Thumbnail") as! NSURL) as NSString
        AppUtilities.lockOrientation(.portrait)
        self.navigationController?.pushViewController(view, animated: true)
        //navi.pushViewController(view, animated: true)

    }

    //MARK:- Scrolling Methods

    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        self.ImageCollectionview .stopScrolling()
        if !decelerate {
            print(decelerate)
            stopTimer()
            self.perform(#selector(self.startTimer), with: nil, afterDelay: 5.0)
        }else{
            stopTimer()
        }
    }

    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        self.ImageCollectionview .stopScrolling()
        isscrolling = false
        if isscrolling == false{
            self.perform(#selector(self.startTimer), with: nil, afterDelay: 5.0)
        }

    }

    //MARK:- Timer Init and Close

    func startTimer() {

        if Globaltimer == nil {
            Globaltimer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(self.loop), userInfo: nil, repeats: false)
            print("timer start")
        }
    }

    func stopTimer() {
        if Globaltimer != nil {

            Globaltimer?.invalidate()
            Globaltimer = nil
            print("timer Stop")
        }
    }

    func loop() {
        self.ImageCollectionview .startScrolling()

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    //MARK:- Collectionview method

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
    {
        if (self.arr_responseObject.count > 0 ){
            return self.arr_responseObject.count
        }else{
            return 0
        }

    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
    {
        // get a reference to our storyboard cell
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PhotoCell",for: indexPath as IndexPath)
        let dict : NSDictionary = self.arr_responseObject[indexPath.row] as! NSDictionary
        let img_view = cell.viewWithTag(20) as! UIImageView
        img_view.contentMode = .scaleAspectFit
        img_view.downloadImageFrom((dict["urls"] as! NSDictionary)["small"] as! String, contentMode: .scaleAspectFit)

        return cell
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
    {
        let dict : NSDictionary = self.arr_responseObject[indexPath.row] as! NSDictionary
        let arrSend : NSMutableArray = NSMutableArray()
        for index in 0..<self.arr_responseObject.count{
            let dictTemp : NSDictionary = self.arr_responseObject[index] as! NSDictionary
            let imageInfo = JTSImageInfo()
            imageInfo.istrading = "0"
            imageInfo.imageURL = URL(string: ((dictTemp.value(forKeyPath: "urls") as! NSDictionary).value(forKeyPath: "regular") as! NSString) as String)
            imageInfo.title = ((dictTemp.value(forKeyPath: "user") as! NSDictionary).value(forKey: "name") as! NSString) as String!
            imageInfo.thumbnail = ((dictTemp.value(forKeyPath: "urls") as! NSDictionary).value(forKeyPath: "thumb") as! NSString) as String!
            imageInfo.altText = ((dictTemp.value(forKeyPath: "user") as! NSDictionary).value(forKey: "links") as! NSDictionary).value(forKeyPath: "html") as! String!
            arrSend.add(imageInfo)

        }
        let imageInfo = JTSImageInfo()
        AppUtilities.sharedInstance.SetBoolForObserver(str: "NewPhoto", value: "1")
        let previewurl = ((dict.value(forKeyPath: "urls") as! NSDictionary).value(forKeyPath: "full") as! NSString) as String

        print(previewurl)
        let newpreview = previewurl.replacingOccurrences(of: "q=85", with: "q=60&w=1000&h=1000")
        print(newpreview)
        imageInfo.imageURL = URL(string: newpreview)
        imageInfo.title = ((dict.value(forKeyPath: "user") as! NSDictionary).value(forKey: "name") as! NSString) as String!
        imageInfo.thumbnail = ((dict.value(forKeyPath: "urls") as! NSDictionary).value(forKeyPath: "full") as! NSString) as String!
        imageInfo.altText = ((dict.value(forKeyPath: "user") as! NSDictionary).value(forKey: "links") as! NSDictionary).value(forKeyPath: "html") as! String!
        imageInfo.istrading = "0"
        let photoid = indexPath.row
        let imageViewer = JTSImageViewController(imageInfo: imageInfo, arry: arrSend, index: photoid, mode: .image, backgroundStyle: .blurred)
        imageViewer?.show(from: self, transition: .center)
        //NotificationCenter.default.post(name: NSNotification.Name("RemoveGestureNewPhoto"), object: nil, userInfo: nil)
    }
    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        lastcellindex = indexPath.row
        if Globaltimer != nil{
            self.ImageCollectionview .startScrolling()
        }
        if self.lastcellindex == self.arr_responseObject.count - 1{
            self.ImageCollectionview.triggerInfiniteScrolling()

        }
    }

    func collectionView(collectionView: UICollectionView,
                        heightForImageAtIndexPath indexPath: IndexPath,
                        withWidth: CGFloat) -> CGFloat {

        let dict : NSDictionary = self.arr_responseObject[indexPath.row] as! NSDictionary
        let actualWidth = dict["width"] as? Int ?? 1
        let actualHeight = dict["height"] as? Int ?? 1
        let actualRatio : Float = Float(actualWidth) / Float(actualHeight)
        let framesize : Float = Float(collectionView.frame.size.width - 10) / Float(3)

        return CGFloat(framesize / actualRatio)
    }

    func collectionView(collectionView: UICollectionView,
                        heightForAnnotationAtIndexPath indexPath: IndexPath,
                        withWidth: CGFloat) -> CGFloat {

        return 0
    }
    //MARK:- WebService Call
    func callWebserviceAuthorize(pageindex : Int , Pagesize : Int){

        if AppUtilities.sharedInstance.isNetworkRechable(){
            IsFinish = true
             let url = "https://api.unsplash.com/photos/?page=\(pageindex)&per_page=\(Pagesize)&order_by=new&client_id=\(APP_ID)"


            print(url)

            manager.responseSerializer = AFHTTPResponseSerializer()
            manager.get(
                url,
                parameters: nil,
                success:
                {
                    (operation, responseObject) in
                    let json = try? JSONSerialization.jsonObject(with: responseObject as! Data, options: [])

                    if let arr : NSArray = json as? NSArray
                    {
                        if self.pageCount == 1
                        {
                            self.LightHeaderView.alpha = 1.0
                            UIView.animate(withDuration: 5.0, animations: {
                                self.LightHeaderView.alpha = 0.0
                                self.view.layoutIfNeeded()

                            })

                            self.ImageCollectionview.stopScrolling()
                            self.arr_responseObject.removeAllObjects()
                        }else{

                        }
                        self.arr_responseObject.addObjects(from: NSMutableArray(array: arr) as! [Any])
                       print(self.arr_responseObject.value(forKeyPath: "urls") as? NSArray)
                        self.IsFinish = false
                        self.ImageCollectionview.infiniteScrollingView.stopAnimating()
                        self.ImageCollectionview.reloadData()
                        if self.pageCount == 1
                        {
                            if self.isAppfirst != false{
                                self.perform(#selector(self.startTimer), with: nil, afterDelay: 0.3)
                            }
                        }
                    }
                    GIFProgressHUD .hide(for: self.view, animated: true)
            },
                failure:
                {
                    (operation, error) in

                    print("Error: " + (error?.localizedDescription)!)
                    self.IsFinish = false
                    AppUtilities.sharedInstance.showAlert(title: "Error", msg: (error?.localizedDescription)! as NSString)
                    self.callWebserviceAuthorize(pageindex: self.pageCount, Pagesize:  self.pageSize)
                    self.stopTimer()

            })

        }else{
            AppUtilities.sharedInstance.showAlert(title: "No Internet", msg: "No Internet Connection . please check your Internet.")
        }
    }
}
Himanshu Moradiya
  • 4,769
  • 4
  • 25
  • 49