Как добавить жест смахивания или функцию смахивания между двумя представлениями контейнера перекрытия, используя сегментированный элемент управления, например, профиль Instagram? - PullRequest
0 голосов
/ 11 марта 2020

Я новичок в iOS и пытаюсь создать приложение, чтобы узнать больше. Я застрял на последнем этапе моего заявления. Я хочу иметь возможность провести между двумя представлениями контейнера с использованием сегментированного управления. Я хочу добавить два перекрывающихся вида контейнера (виды контейнера с переходом на внедрение с дочерним контроллером) одинакового размера на половину экрана в одном контроллере, например в профиле Instagram. Я хочу добавить просмотр таблицы для обоих дочерних контроллеров. Когда я запускаю приложение, должны быть видны данные первого дочернего представления, но когда я проведу пальцем влево, второй дочерний контроллер должен быть виден с тем же размером и в том же положении. Я хочу, чтобы это было похоже на профиль Instagram.

В настоящее время, когда я проводлю пальцем влево, второй дочерний контроллер открывается в полноэкранном режиме и скрывает все остальное на этом экране. Я пробовал различные уроки, но безрезультатно. Можете ли вы помочь мне сделать это?

Спасибо!

Это код контроллера моего представления // CODE //

{

//

//  ViewController.swift
//  BeautyParlor
//
//  Created by Mohammad Affan Siddiqui on 20/11/2019.
//  Copyright © 2019 Mohammad Affan Siddiqui. All rights reserved.
//
import UIKit
//import PinterestLayout
class ViewController: UIViewController {
    @IBOutlet weak var SegmentedControl: UISegmentedControl!

    @IBOutlet weak var thirdView: UIView!
    @IBOutlet weak var collectionViewOutletPortfolio: UICollectionView!
    @IBOutlet weak var collectionViewOutletAbout: UICollectionView!
    @IBOutlet weak var secondView: UIView!
    @IBOutlet weak var firstView: UIView!

    @IBOutlet weak var collectionViewOutletStatic: UICollectionView!

   // FOR STATIC DATA
    var arrimgbackground = [UIImage]()
    var arrimglogo = [UIImage]()
    var arrimglocation = [UIImage]()
    var arrimginsta = [UIImage]()
    var arrlblname = ["ABC Saloon"]
    var arrlblrating = ["Rating 4.5/5"]
    var arrlbllocation = ["ABC,Street,karachi"]
    var arrlblinsta = ["qqq"]
    var  arrlblservicename = ["We are serving you"]
    var arrlblrs = ["Rs:200"]

      // FOR ABOUT DATA
    var arrlbldescription = ["Before you can begin to determine what the will grow. The whole process is an organic one—a natural progression from a seed to a full-blown "]


    // FOR PORTFOLIO DATA

    var arrimgportfolio = [UIImage]()





    override func viewDidLoad() {
        super.viewDidLoad()



//       
//
//
//
//        setupSegmentedContrl()
        setupHorizontalBar()

//        let swipright = UISwipeGestureRecognizer(target: self, action: #selector(self.swipGesture))
//        swipright.direction = UISwipeGestureRecognizer.Direction.right
//        self.thirdView?.addGestureRecognizer(swipright)

//        let rightSwipe = UISwipeGestureRecognizer(target: SegmentCotroller, action: Selector("swiped:"))
//           rightSwipe.direction = .Right
//           self.SegmentCotroller.addGestureRecognizer(rightSwipe)
//

        let rightSwipe = UISwipeGestureRecognizer(target: self, action: Selector(("swiped:")))
        rightSwipe.direction = .right
        self.secondView?.addGestureRecognizer(rightSwipe)
//        let swipright = UISwipeGestureRecognizer(target: self, action: #selector(self.swipGesture))
//        swipright.direction = UISwipeGestureRecognizer.Direction.right
//        self.secondView?.addGestureRecognizer(swipright)
//
//
//        let layout = PinterestLayout()
//        collectionViewOutletPortfolio.collectionViewLayout = layout
//
//        layout.delegate = self
//        layout.cellPadding = 5
//        layout.numberOfColumns = 2
//
//

//
//       if let layout = collectionViewOutletPortfolio?.collectionViewLayout as? PinterestLayout {
//        layout.delegate = self as! PinterestLayoutDelegate
//       }
//

        thirdView?.isHidden = true

        arrimgbackground = [#imageLiteral(resourceName: "d.png")]
        arrimglogo = [#imageLiteral(resourceName: "roundimage.png")]
        arrimglocation = [#imageLiteral(resourceName: "location.jpeg")]
        arrimginsta = [#imageLiteral(resourceName: "insta.png")]
        arrimgportfolio = [#imageLiteral(resourceName: "c.png"), #imageLiteral(resourceName: "d.png"), #imageLiteral(resourceName: "down.png"), #imageLiteral(resourceName: "down.png"), #imageLiteral(resourceName: "c.png"), #imageLiteral(resourceName: "c.png"), #imageLiteral(resourceName: "c.png"), #imageLiteral(resourceName: "c.png"), #imageLiteral(resourceName: "d.png"), #imageLiteral(resourceName: "d.png"), #imageLiteral(resourceName: "d.png"), #imageLiteral(resourceName: "d.png"), #imageLiteral(resourceName: "down.png"), #imageLiteral(resourceName: "down.png"), #imageLiteral(resourceName: "down.png")]

       // setupSegmentedControl().topAnchor.constraintEqualToAnchor(topLayoutGuide)
    }


    private func setupHorizontalBar(){

    }

    private func setupSegmentedControl(){


    }
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
       // SegmentedControl
    }

//    @objc func swipGesture(sender: UISwipeGestureRecognizer?){
// //   @objc func swipeAction (swipe: UISwipeGestureRecognizer) {
//      if let swipGesture = sender{
//        switch swipGesture.direction {
//        case  UISwipeGestureRecognizer.Direction.right:
//                print ("i just swip right")
//                let redVC = UIViewController()
//                redVC.view.backgroundColor = UIColor.red
//                //self.navigationController?.popViewController(animated: true)
//            //performSegue(withIdentifier: "goRight", sender: self)
//        default:
//            break
//        }
//    }
//
//    }
              //  thirdView = uivi(frame: thirdView)
                                //self.collectionViewOutletPortfolio? = UICollectionView()
//                ViewController.swipGesture(index: index)(index: index)
//           case UISwipeGestureRecognizer.Direction.left:

//                print ("i just swiped left")
////
//               // arrlbl  = UICollectionView()
//            default:
//                break
//
//            }
//        }





    // FOR SWIPPING CHECK WORKING OR NOT
//    @IBAction func swipBetweenViews(_ sender: UISwipeGestureRecognizer) {
//      print ("HelowSwipped")
//
//}

    @IBAction func switchViews(_ sender: UISegmentedControl) {

    if sender.selectedSegmentIndex == 0{
        firstView.isHidden = false
        secondView?.isHidden = false
        thirdView?.isHidden = true
//            firstView.alpha = 0
//            secondView.alpha = 1
//            thirdView.alpha = 0
//
        }else{
        firstView.isHidden = false
        secondView?.isHidden = true
        thirdView?.isHidden = false
//            firstView.alpha = 0
//            secondView.alpha = 0
//            thirdView.alpha = 1
        }
    }

}
extension ViewController: UICollectionViewDataSource , UICollectionViewDelegate{

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if (collectionView == collectionViewOutletStatic){
            let cell = collectionViewOutletStatic.dequeueReusableCell(withReuseIdentifier: "cellone", for: indexPath)as! CollectionViewCellStatic
            cell.imgbackground.image = arrimgbackground[indexPath.row]
            cell.imglogo.image = arrimglogo[indexPath.row]
            cell.imglocation.image = arrimglocation[indexPath.row]
            cell.imginsta.image = arrimginsta[indexPath.row]
            cell.lblname.text = arrlblname[indexPath.row]
            cell.lblrating.text = arrlblrating[indexPath.row]
            cell.lbllocation.text = arrlbllocation[indexPath.row]
            cell.lblinstaname.text = arrlblinsta[indexPath.row]
            cell.lblservicename.text = arrlblservicename[indexPath.row]
            cell.lblrs.text = arrlblrs[indexPath.row]
            return cell
        }else{
            if (collectionView == collectionViewOutletAbout){
                let cello = collectionViewOutletAbout.dequeueReusableCell(withReuseIdentifier: "celltwo", for: indexPath)as! CollectionViewCellAbout
                           cello.lbldescription.text = arrlbldescription[indexPath.row]
                           return cello
            }else{
                let cellt = collectionViewOutletPortfolio?.dequeueReusableCell(withReuseIdentifier: "cellthree", for: indexPath)as! CollectionViewCellPortfolio
                cellt.imgPortfolio.image = arrimgportfolio[indexPath.row]
                return cellt



                  // THIS CODE FOR 3 COLUMNS OF IMAGES COLLECTION LIKE PORFOLIO
//              _ = UIScreen.main.bounds.width/2-2
//                       let layout = UICollectionViewFlowLayout()
//
//                       collectionViewOutletPortfolio?.collectionViewLayout = layout
//
//                               layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
//                     // layout.itemSize = CGSize(width: itemSize, height: itemSize)
////
////                       layout.minimumInteritemSpacing = 0
////                       layout.minimumLineSpacing = 0

            }

        }
    }


    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
//        let x = CGFloat(indexPath.item) * frame.width
    }


    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if (collectionView == collectionViewOutletStatic){
            return arrimgbackground.count
        }else{
            if (collectionView == collectionViewOutletAbout){
                return arrlbldescription.count


            }else{
                return arrimgportfolio.count
            }
             }
    }




}
extension ViewController: UICollectionViewDelegateFlowLayout{



    // THIS FOR 3 COLUMNS OF IMAGES IN CLLECTION VIEW CELL
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let collectionwidth = collectionView.bounds.width
        return CGSize(width: collectionwidth/3, height: collectionwidth/3)
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0

    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0
}


}

//extension ViewController: PinterestLayoutDelegate{
//    func collectionView(_ collectionView: UICollectionView, heightForItemAtIndexPath indexPath: IndexPath) -> CGSize {
//        //return UIImage(named: row[indexPath.item].imageename)?.size
//        
//    }
//}
//    


//extension ViewController: PinterestLayoutDelegate{
//    func collectionView(_ collectionView: UICollectionView, heightForItemAtIndexPath indexPath: IndexPath) -> CGFloat {
//        return 100
//    }
//    
//    
//



//  func collectionView(
//      _ collectionView: UICollectionView,
//      heightForPhotoAtIndexPath indexPath:IndexPath) -> CGFloat {
//    return arrimgportfolio[indexPath.row]
//    //return arrimgportfolio[indexPath.item].image.size.height
//  }

1 Ответ

0 голосов
/ 11 марта 2020

Это простой пример, который вы хотите. Это дизайн для полного экрана. Я думаю, что вы можете получить идею и настроить ее под свои требования

class ContainerController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        if #available(iOS 13.0, *) {
            view.backgroundColor = .systemBackground
        } else {
            view.backgroundColor = .white
        }

        navigationItem.titleView = sgControll
        updateView()

        sgControll.addTarget(self, action: #selector(segmentControllValueChanged (_:)), for:.valueChanged)
    }

    //MARK: Components
    let sgControll:UISegmentedControl = {
        let sg = UISegmentedControl()
        sg.insertSegment(withTitle: "first Child", at: 0, animated: true)
        sg.insertSegment(withTitle: "Second Child", at: 1, animated: true)
        sg.selectedSegmentIndex = 0
        return sg
    }()

    private lazy var secondView : SecondChildViewController = {
        let vc = SecondChildViewController()
        self.add(asChildViewController: vc)
        return vc
    }()

    private lazy var firstView:FirstChildViewController = {
        let vc = FirstChildViewwController()
        self.add(asChildViewController: vc)
        return vc
    }()

}


//MARK: Functions
extension ContainerController {

    @objc func segmentControllValueChanged(_ sender : UISegmentedControl){
        print(sender.selectedSegmentIndex)
        updateView()
    }

    private func add(asChildViewController viewController: UIViewController){
        addChild(viewController)
        view.addSubview(viewController.view)
        viewController.view.translatesAutoresizingMaskIntoConstraints = false
        viewController.view.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
        viewController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
        viewController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
        viewController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
        viewController.didMove(toParent: self)
    }

    private func remove(asChildViewController viewController: UIViewController) {
        viewController.willMove(toParent: nil)
        viewController.view.removeFromSuperview()
        viewController.removeFromParent()
    }

private func updateView() {
        if sgControll.selectedSegmentIndex == 0 {
            remove(asChildViewController: firstView)
            add(asChildViewController: secondView)
        } else {
            remove(asChildViewController: seconView)
            add(asChildViewController: firstView)
        }
    }
}
...