Swift 4-如何将两个viewControllers与一个Xib文件一起使用?

时间:2018-05-28 05:34:05

标签: swift

我想知道如何为两个视图控制器使用一个xib文件。可能吗?我做了一些研究,但还没有得到任何具体的答案。我希望你能帮助我。

1 个答案:

答案 0 :(得分:0)

Common XIB

import UIKit

//MARK:- ConfirmationView
/**
 This Class is used to show a common View for limited time
 */
class ConfirmationView: UIView
{
    //MARK: UIView
    /// Main Content View
    @IBOutlet var contentView: UIView!

    //MARK: UILabel
    /// Title to display in View
    @IBOutlet weak var headerLabel: UILabel!

    //MARK: Init Class
    /**
     This function is used to Initialise the class
     */
    override init(frame: CGRect) {
        super.init(frame: frame)
        loadNib()
    }

    //MARK: Encoder
    /**
     This function is used to Store the class objects added
     */
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        loadNib()
    }

    //MARK: Dienit class
    /**
     This function is used to De-Allocate the class objects
     */
    deinit {
        /// Remove all The Initiated Instances
    }
}

//MARK:- Required Functions
extension ConfirmationView
{
    //MARK: Load Nib
    /**
     This function is used to load the Nib from Bundle
     */
    func loadNib() {
        Bundle.main.loadNibNamed("ConfirmationView", owner: self, options: [:])
        // 2. Adding the 'contentView' to self (self represents the instance of a WeatherView which is a 'UIView').
        addSubview(contentView)
        // 3. Setting this false allows us to set our constraints on the contentView programtically
        contentView.translatesAutoresizingMaskIntoConstraints = false
        contentView.backgroundColor = UIColor.clear
        // 4. Setting the constraints programatically
        contentView.topAnchor.constraint(equalTo: topAnchor).isActive = true
        contentView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
        contentView.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
        contentView.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
    }
}

需要设置其大小

enter image description here

enter image description here

<强>用法

主控制器中的

///Create a Reference for XIB

/// Confirmation View Xib Class Reference
private var confirmationViewXib : ConfirmationView?

用法在ViewController中添加为子视图

confirmationViewXib = self.showConfirmationView(staticText: "Sign Up Completed using \(loginType)")
self.view.addSubview(confirmationViewXib!)

显示方法

//MARK: Show ConfirmatonView
/**
  This function is used show the confirmationView Xib with text Passing
 */
func showConfirmationView(staticText:String) -> ConfirmationView
{
    let newView = ConfirmationView.init(frame: self.view.bounds)
    newView.headerLabel.text = staticText
    return newView        
}

注意:实现Delegates或observer从主控制器中的XIB获取输出