在没有导航控制器的同一个viewController中,如何在子视图之间转换?

问题描述

我是iOS开发的新手。我想在 UIKit 的帮助下编写一个页面,该页面可以在子视图之间切换(通过单击单选按钮),并且动画效果不错(如本视频所示: https://www.youtube.com/watch?v=ZXXWkieFzN8)。但是,我不知道该怎么做。我正在尝试在我的重置密码页面中实施此逻辑,以便用户可以选择最佳选项来重置其密码。

解决方法

在标准SDK中,有UIPageViewController https://developer.apple.com/documentation/uikit/uipageviewcontroller

但是,如果您需要自定义动画/视图,则更容易:

  1. 创建所有者UIView,您将在其中更改内容

  2. 为您的自定义内容创建不同的UIView(或UIViewControllers)

  3. 当您需要更改内容时-从固定器中删除以前的UIView,然后插入新的UIView(从而交换它们)。

我尝试使用UIViewControllers代替UIView的内容,因为它更具可重用性。

这是给你的例子

class DynamicViewManager {
    
    private weak var contentView: UIView?
    private(set) weak var currentShownVC: UIViewController?
    
    
    init(contentView: UIView) {
   
        self.contentView = contentView
    }
    
    
    func show(viewController: UIViewController) {
        
        guard let contentView = self.contentView else {
            
            return
        }
        
        viewController.view.translatesAutoresizingMaskIntoConstraints = false
        
        self.removePresentedVC()
        self.currentShownVC = viewController
        
        contentView.addSubview(viewController.view)
        contentView.sendSubviewToBack(viewController.view)
        NSLayoutConstraint.activate(self.pinningConstraints(view: viewController.view,to: contentView))
    }
    
    
    @discardableResult
    func removePresentedVC() -> UIViewController? {
        
        let cached = self.currentShownVC
        self.currentShownVC?.view.removeFromSuperview()
        self.currentShownVC = nil
        return cached
    }

    private func pinningConstraints(view: UIView,to anotherView: UIView) -> [NSLayoutConstraint] {
    
      return [
            view.leadingAnchor.constraint(equalTo: anotherView.safeAreaLayoutGuide.leadingAnchor),view.trailingAnchor.constraint(equalTo: anotherView.safeAreaLayoutGuide.trailingAnchor),view.topAnchor.constraint(equalTo: anotherView.safeAreaLayoutGuide.topAnchor),view.bottomAnchor.constraint(equalTo: anotherView.safeAreaLayoutGuide.bottomAnchor)
        ]
    }
}

在您的情况下,看起来像这样

let manager = DynamicViewManager(contentView: self.contentView)
let left = LeftViewController()
let right = RightViewController()
.onLeftClick {
    manager.show(left) 
    self.changeHeight(for: contentView,toPercentage: 15)
}

.onRightClick {
    manager.show(right)
    self.changeHeight(for: contentView,toPercentage: 30)
}

您还可以调整ContentView的高度,以便将所有内容显示在下面(重置密码也移到顶部)

您可以通过停用先前的约束并激活新的约束来更改高度(以使self.changeHeight起作用)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...