如何在swift中按下按钮从另一个xib文件加载另一个xib文件

问题描述 投票:0回答:2

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

enter image description here

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

}
ios swift uiview xib
2个回答
0
投票

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

(按下按钮)

让customInfoView = CustomInfoView()

self.addSubview(customInfoView)

然后当你需要解雇它时,只需将其从父项中删除即可。


0
投票

你可以这样做:

@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,以便您可以轻松删除它。

© www.soinside.com 2019 - 2024. All rights reserved.