ios - 如何将 Storyboard中的 subview 添加到 swift 4 代码中的另一个 View ?

标签 ios swift uiview swift4 subviews

我创建了一个在 Storyboard中的 View ,我想将这个 View 添加到另一个不在 Storyboard中的 View ,它是用代码创建的 这是我的代码:

@IBOutlet weak var sideBarView: UIView!
var sideBarViews = UIView()
override func viewDidLoad() 
{
     super.viewDidLoad()
     self.sideBarViews.frame = CGRect(x:UIScreen.main.bounds.width  , y: 0, width: UIScreen.main.bounds.width / 2, height: UIScreen.main.bounds.height)
     self.sideBarViews.backgroundColor = UIColor.init(red: 251/255, green: 251/255, blue: 251/255, alpha: 1.0)
     UIApplication.shared.keyWindow!.addSubview(self.sideBarViews)
     UIApplication.shared.keyWindow!.bringSubview(toFront: self.sideBarViews)
     self.view.bringSubview(toFront: self.sideBarViews)
}
@IBAction func sideBarMenu(_ sender: UIBarButtonItem)
{
    UIView.animate(withDuration: 0.3, animations:
    {
      UIApplication.shared.keyWindow!.addSubview(self.sideBarViews)
      UIApplication.shared.keyWindow!.bringSubview(toFront: self.sideBarViews)
      self.view.bringSubview(toFront: self.sideBarViews)
      self.sideBarViews.frame = CGRect(x:UIScreen.main.bounds.width / 2 , y: 0, width: UIScreen.main.bounds.width / 2, height: UIScreen.main.bounds.height)
      self.view.addSubview(self.sideBarView)
      UIApplication.shared.keyWindow!.addSubview(self.sideBarView)
      UIApplication.shared.keyWindow!.bringSubview(toFront: self.sideBarView)
      self.view.bringSubview(toFront: self.sideBarView)
      self.view.layoutIfNeeded()
    })
}

最佳答案

UIViewController 中的 Storyboard 中创建的 UI 组件的问题是它们不可重用且不可子类化。此外,特定 Storyboard 中的 UIViewControllers 不能被子类化,以后也不能像其他类一样重用。

我建议考虑创建一个带有专用 UIView 子类的 .xib 文件,以便您可以随时重用它。

这里有一个很好的教程 - https://medium.com/@brianclouser/swift-3-creating-a-custom-view-from-a-xib-ecdfe5b3a960

关于ios - 如何将 Storyboard中的 subview 添加到 swift 4 代码中的另一个 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48183439/

相关文章:

ios - 自定义 View - 在 "required init?(coder aDecoder: NSCoder)"方法中崩溃

ios - 如何从 imagePickerController 执行推送 segue?

swift - 设置文本以适合 UILabel 的大小并在 SWIFT 中居中

ios - 我什么时候应该在 UIViews 中设置边框?

swift - 与 NavigationView 结合添加滚动

ios - 如何避免旋转动画在 2π 边界跳跃?

ios - 通知被点击后如何从屏幕上移除

iOS - 动态更改字体大小

ios - subview 如何识别父 View (iPhone)的设置属性?

ios - 为什么我需要在 drawInRect 中调用 glClear?