按下按钮,将UIViewController .xib添加到UIViewController

时间:2017-09-18 14:09:40

标签: swift swift3 uiviewcontroller

在我的游戏中,我有一个ViewController,它在一个collectionView中显示各种项目,我需要这样做,以便在索引处按下一个项目时...

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    // handle tap events
    if indexPath.item == 0 {
        //add a viewcontroller for viewing content
        //other things here for customizing that view data
    }
}

...一个viewcontroller在屏幕上弹出,不占用整个屏幕,而是在主ViewController中间的一小部分

(我需要视图可重用和适应性)我已经尝试制作一个viewController并将其添加到主ViewController作为各种子视图但没有运气

我希望显示不同的信息,具体取决于您选择的单元格,如果您可以帮助我,我会很感激

1 个答案:

答案 0 :(得分:1)

据我了解,您希望打开自定义视图,该视图在ViewControllers视图上从xib加载,或者在ViewController上显示不同的ViewControllers视图(在collectionView中显示各种项目)。

如果是,则使用以下代码

//Create optional property 

 var myViewController : YourCustomViewController?


func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// handle tap events
         if indexPath.item == 0 {
    //add below line to load custom View Xib 
    loadCustomView(onView:self.view)                                       
    //OR To Add ViewController View use below code
    loadViewController(onView:self.view)
  }
}

 fun loadCustomView(onView:UIView) {
     let allViewsInXibArray = Bundle.init(for: type(of: self)).loadNibNamed("CustomView", owner: self, options: nil)
    //If you only have one view in the xib and you set it's class to MyView class
    let myCustomView = allViewsInXibArray?.first as! CustomView
    onView addSubview(myCustomView)
    addConstraints(onView: myCustomView)

}

 func loadViewController(onView:UIView) {
     myViewController = YourCustomViewController(nibName: "TestViewController", bundle: nil);
    onView addSubview((myViewController?.view)!)
    addConstraints(onView: (myViewController?.view)!)

}

func addConstraints(onView : UIView) {
    onView.translatesAutoresizingMaskIntoConstraints = false;

    let widthConstraint = NSLayoutConstraint(item: onView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal,
                                             toItem: onView.superview, attribute: .width, multiplier: 0.8, constant: 0)
    let heightConstraint = NSLayoutConstraint(item: onView, attribute: .height, relatedBy: .equal,
                                              toItem: onView.superview, attribute: .height, multiplier: 0.6, constant: 0)
    let xConstraint = NSLayoutConstraint(item: onView, attribute: .centerX, relatedBy: .equal, toItem:onView.superview , attribute: .centerX, multiplier: 1, constant: 0)
    let yConstraint = NSLayoutConstraint(item: onView, attribute: .centerY, relatedBy: .equal, toItem: onView.superview, attribute: .centerY, multiplier: 1, constant: 0)
    NSLayoutConstraint.activate([widthConstraint, heightConstraint, xConstraint, yConstraint])

}

此外,您可以将弹出窗口和弹出式动画添加到自定义视图中。

如果您还有其他需要,请评论我。