我正在使用 UIView
的两个 xib
文件。我想在第一个 xib
View (即 FirstView
)按下按钮时显示 Custominfoview
。我在这里有点困惑如何做到这一点。我的代码如下,请告诉我该怎么做。我已经搜索了很多但没有找到。我在链接中附上了一张我真正想要的图片。
class CustominfoView: UIView {
@IBOutlet var mainCustomView: UIView!
@IBOutlet weak var infotextLbl: UILabel!
// MARK:-
// MARK:- Methods
// MARK: UIView Methods
required init(coder aDecoder : NSCoder) {
super.init(coder :aDecoder)!
setup()
}
override init(frame : CGRect) {
super.init(frame: frame)
setup()
}
func setup() {
let view = loadViewFromXib()
view.frame = bounds
// view.autoresizingMask = UIViewAutoresizing.flexibleWidth | UIViewAutoresizing.flexibleHeight
view.layer.cornerRadius = 12
view.layer.borderColor = UIColor.red.cgColor
view.layer.borderWidth = 2
addSubview(view)
}
func loadViewFromXib() -> UIView {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: "CustominfoView", bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
return view
}
}
class FirstView: UIView {
@IBOutlet var mainCustomView: UIView!
@IBOutlet weak var infotextLbl: UILabel!
// MARK:-
// MARK:- Methods
// MARK: UIView Methods
required init(coder aDecoder : NSCoder) {
super.init(coder :aDecoder)!
setup()
}
override init(frame : CGRect) {
super.init(frame: frame)
setup()
}
func setup() {
let view = loadViewFromXib()
view.frame = bounds
// view.autoresizingMask = UIViewAutoresizing.flexibleWidth | UIViewAutoresizing.flexibleHeight
view.layer.cornerRadius = 12
view.layer.borderColor = UIColor.red.cgColor
view.layer.borderWidth = 2
addSubview(view)
}
func loadViewFromXib() -> UIView {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: "CustominfoView", bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
return view
}
@IBAction func infoBtnpressed(_ sender: UIButton) {
print("Pressed")
}
}
}
最佳答案
只需使用 addSubview 将 customInfoView 添加为第一个 View 顶部的 subview 即可。
(按下按钮)
让customInfoView = CustomInfoView()
self.addSubview(customInfoView)
然后,当您需要关闭它时,只需将其从父级中删除即可。
关于ios - 如何在 swift 中按下按钮时从另一个 xib 文件加载另一个 xib 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51531959/