繁体   English   中英

如何快速按下按钮从另一个xib文件加载另一个xib文件

[英]how to load another xib file from another xib file on pressing button in swift

我正在使用UIView两个xib文件。 我想从第一个xib视图(即Custominfoview中按按钮显示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")
    }
}

}

只需使用addSubview将customInfoView作为子视图添加到第一个视图的顶部。

(按下按钮)

让customInfoView = CustomInfoView()

self.addSubview(customInfoView)

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

您可以执行以下操作:

@IBAction func infoBtnpressed(_ sender: UIButton) {
    print("Pressed")
    let customInfoView = CustomInfoView(frame: CGRect(x: 100, y: 100, width: 200, height: 200) )
    self.addSubView(customInfoView)
}

CGRect ,根据需要传递帧值。 另外,您应该将customInfoView声明为global以便可以轻松将其删除。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM