【问题标题】:How to set the positions and size of custom XIB View into the main View Controller?如何将自定义 XIB 视图的位置和大小设置到主视图控制器中?
【发布时间】:2018-11-07 07:52:36
【问题描述】:

我用 xib 制作了自定义视图类,并从 xib 加载了这个 UIView 类。它显示了这个 xib,但没有在 ViewController.swift 中设置 UIView 的高度和宽度。

CustomView.swift

class CustomView: UIView {

    @IBOutlet weak var contentView: UIView!

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupView()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupView()
    }

    func setupView() {
        Bundle.main.loadNibNamed("CustomView", owner: self, options: nil)
        self.addSubview(contentView)
    }

}

ViewController.Swift

Class ViewController: UIViewController {
        @IBOutlet weak var view1: UIView!

        override func viewDidLoad() {
            super.viewDidLoad()

            let customView = CustomView()
            customView.frame = view1.frame
            view1.addSubview(customView)
        }
    }

【问题讨论】:

    标签: ios swift uiview xib addsubview


    【解决方案1】:

    我会在自定义视图的初始化中采用一些不同的方法。代码如下:

    自定义视图:

    class CustomView: UIView {
    
        @IBOutlet weak var contentView: UIView!
    
        class func instanceFromNibWithFrame(_ frame: CGRect) -> UIView {
            guard let view = UINib(nibName: "CustomView", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as ?UIView else {
                fatalError("CustomView can't be init")
            }
        view.frame = frame
        return view
        }
    }
    

    视图控制器:

    class ViewController: UIViewController {
        @IBOutlet weak var view1: UIView!
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            let customView = CustomView.instanceFromNibWithFrame(view1.bounds)
            view1.addSubview(customView)
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-29
      • 1970-01-01
      • 1970-01-01
      • 2011-09-22
      • 1970-01-01
      • 1970-01-01
      • 2016-02-10
      • 2016-02-01
      相关资源
      最近更新 更多