首页 > 解决方案 > 如何在swift中按下按钮时从另一个xib文件加载另一个xib文件

问题描述

我正在使用xib两个UIView. 我想Custominfoview从第一个视图显示按下按钮xib,即FirstView. 我在这里有点困惑如何做到这一点。我的代码如下,请告诉我该怎么做。我搜索了很多,但没有找到。我在链接中附上了一张我想要的图片。

在此处输入图像描述

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")
    }
}

}

标签: iosswiftuiviewxib

解决方案


只需使用 addSubview 在第一个视图之上添加 customInfoView 作为子视图。

(按下按钮)

让 customInfoView = CustomInfoView()

self.addSubview(customInfoView)

然后,当您需要将其关闭时,只需将其从父级中删除即可。


推荐阅读