使用 UIPageViewController 的最佳方法或技术是什么

问题描述 投票:0回答:1

import Foundation
import UIKit

class HomeVC: UIViewController {
    
    //MARK: - Outlet
    
    @IBOutlet weak var tblView: UITableView!
    //------------------------------------------------------
    
    //MARK: - Class Variable
    private var viewModel : HomeVM = HomeVM()
    var currentPage = 1
    let refreshControl = UIRefreshControl()
    let reachability = try! Reachability()
    //------------------------------------------------------
    
    //MARK: - Memory Management Method
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
        
    deinit {
        debugPrint("‼️‼️‼️ deinit : \(self.classForCoder) ‼️‼️‼️")
    }
    
    //------------------------------------------------------
    
    //MARK: - Life Cycle Method
    
    override func viewDidLoad() {
        super.viewDidLoad()
//        setUpView()
    }

    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        setUpView()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
    }
    //------------------------------------------------------
              
    //MARK: - Custom Method
    
    private func setUpView() {
        self.applyStyle()
        self.setupViewModelObserver()
        self.viewModel.apiCallHome(page: currentPage)
        self.showToast(message: "Page \(currentPage)", font: .systemFont(ofSize: 17.0))
    }
    
    private func applyStyle(){
        self.tblView.separatorStyle = .none
        
        refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")
        refreshControl.addTarget(self, action: #selector(self.refresh(_:)), for: .valueChanged)
        tblView.addSubview(refreshControl)
    }
    @objc func refresh(_ sender: AnyObject) {
       // Code to refresh table view
        self.currentPage = 1
        self.viewModel.apiCallHome(page: currentPage)
        self.showToast(message: "Page \(currentPage)", font: .systemFont(ofSize: 17.0))
        self.refreshControl.endRefreshing()
    }
    /**
     Setup all view model observer and handel data and erros.
     */
    private func setupViewModelObserver() {
        viewModel.eventHandler = { events in
            switch events {
            case .startLoading:
                debugPrint("Start_Loading")
            case .stopLoading:
                debugPrint("Stop_Loading")
            case .dataLoaded:
                DispatchQueue.main.async {
                    self.tblView.reloadData()
                }
            case .message( let error):
                debugPrint(error as Any)
            }
        }
    }
    
    //------------------------------------------------------
       
    //MARK: - Action Method
      
    //------------------------------------------------------
    
}

//MARK: - UITableViewDelegate and DataSource Methods -
extension HomeVC: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.viewModel.arrHomeData.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "HomeTblCell", for: indexPath) as! HomeTblCell
        let data = self.viewModel.arrHomeData[indexPath.row]
        cell.imgAvatar.setImage(with: data.avatar ?? "")
        cell.lblFname.text = data.firstName
        cell.lblLName.text = data.lastName
        indexPath.row % 2 == 0 ? (cell.vwContainer.backgroundColor = UIColor.systemGray6) : (cell.vwContainer.backgroundColor = UIColor.systemGray3)
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let vc = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "PageVC") as! PageVC
        let data = self.viewModel.arrHomeData[indexPath.row]
        vc.imageName = data.avatar
        vc.fName = data.firstName
        vc.lName = data.lastName
        vc.email = data.email
        self.navigationController?.pushViewController(vc, animated: true)
    }
                
//    func scrollViewDidScroll(_ scrollView: UIScrollView) {
//            let height = scrollView.frame.size.height
//            let contentYoffset = scrollView.contentOffset.y
//            let distanceFromBottom = scrollView.contentSize.height - contentYoffset
//            if distanceFromBottom < height {
//                print("you reached end of the table")
//                self.currentPage = 2
//                self.viewModel.apiCallHome(page: currentPage)
//                self.showToast(message: "Page \(currentPage)", font: .systemFont(ofSize: 17.0))
//            }
//    }
    
    func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
        let offset: CGPoint = scrollView.contentOffset
        let bounds: CGRect = scrollView.bounds
        let size: CGSize = scrollView.contentSize
        let inset: UIEdgeInsets = scrollView.contentInset
        let y: CGFloat = offset.y + bounds.size.height - inset.bottom
        let h: CGFloat = size.height
        //        print("offset: %f", offset.y)
        //        print("content.height: %f", size.height)
        //        print("bounds.height: %f", bounds.size.height)
        //        print("inset.top: %f", inset.top)
        //        print("inset.bottom: %f", inset.bottom)
        //        print("position: %f of %f", y, h)
        
        let reloadDistance: CGFloat = 30
        
        if (y > h + reloadDistance) {
            print("load more rows")
            self.currentPage = 2
            self.viewModel.apiCallHome(page: currentPage)
            self.showToast(message: "Page \(currentPage)", font: .systemFont(ofSize: 17.0))
        }
    }
      
    private func isLastCell(indexPath: IndexPath) -> Bool {
        print(indexPath)
        if self.viewModel.arrHomeData.count > 0 {
            return ((indexPath.section == indexPath.section-1) && (indexPath.row == (self.viewModel.arrHomeData.count-1)))
        } else {
            return false
        }
    }
}


extension UIViewController {

func showToast(message : String, font: UIFont) {
    let toastLabel = UILabel(frame: CGRect(x: self.view.frame.size.width/2 - 75, y: self.view.frame.size.height-100, width: 150, height: 35))
    toastLabel.backgroundColor = UIColor.black.withAlphaComponent(0.6)
    toastLabel.textColor = UIColor.white
    toastLabel.font = font
    toastLabel.textAlignment = .center
    toastLabel.text = message
    toastLabel.alpha = 1.0
    toastLabel.layer.cornerRadius = 10
    toastLabel.clipsToBounds  =  true
    self.view.addSubview(toastLabel)
    UIView.animate(withDuration: 4.0, delay: 0.1, options: .curveEaseOut, animations: {
         toastLabel.alpha = 0.0
    }, completion: {(isCompleted) in
        toastLabel.removeFromSuperview()
    })
} }

我已经尝试过上述方法,是否还有其他方法可以在单个 ViewController 中使用 UIPageViewController 。 P.S:- 我不想为 UIPageViewController 创建单独的类,我只想按照上述方法使用它,所以如果有人知道使用此技术执行此操作的正确方法,请分享。

ios swift uipageviewcontroller
1个回答
0
投票

您的问题标题询问的是

UIPageViewController
,但您发布的代码(近 200 行)不包含任何对
UIPageViewController
的引用。然后你说“......我只想像上面的方法一样使用它......”鉴于你的代码根本不使用页面视图控制器,那是什么方法?

您可以按原样使用页面视图控制器,也可以根据需要对其进行子类化。正如 DonMag 在他链接的答案中引用的那样,如果需要,您可以将页面视图控制器的视图作为另一个视图控制器的子视图。

我的建议是:创建一个客户视图控制器,其中包含

UIPageViewController
作为子视图。让父视图控制器设置并管理父页面上的其他视图(如果需要)。 (当用户切换页面时不会改变的部分。)同时让父级充当
UIPageViewController
的委托。

© www.soinside.com 2019 - 2024. All rights reserved.