我创建了一个在 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/