Creating a UIView subclass with optional IBOutlets

时间:2017-04-24 17:35:22

标签: ios swift uiview xib iboutlet

I am trying to implement a Custom UIView called MediaView.

Inside, I will have a loading indicator by default. On top of it, either an image, a GIF or a video will be shown. Only one IBOutlet will be drawn there.

How can I achieve this?

class MediaView: UIView{

@IBOutlet weak var loadingIndicator : LoadingActivityIndicator!

@IBOutlet weak var apngImageView : APNGImageView?
@IBOutlet weak var animatedImageView : AnimatedImageView?
@IBOutlet weak var player : Player?

// MARK: - Initializers

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

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

// MARK: - Private Helper Methods

// Performs the initial setup.
private func setupView() {
    let view = viewFromNibForClass()
    view.frame = bounds

    // Auto-layout stuff.
    view.autoresizingMask = [
        UIViewAutoresizing.FlexibleWidth,
        UIViewAutoresizing.FlexibleHeight
    ]

    // Show the view.
    addSubview(view)
}

// Loads a XIB file into a view and returns this view.
private func viewFromNibForClass() -> UIView {

    let bundle = Bundle(for: type(of: self))
    let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle)
    let view = nib.instantiate(withOwner: self, options: nil).first as! UIView

    return view
}

}

1 个答案:

答案 0 :(得分:1)

如果你真的想要从层次结构中删除视图(而不是隐藏它们),那么有两个"直截了当的"如何解决这个问题:

  1. 当你告诉你的子类" init"本身适用于"图像类型,"只需在您不再需要的两个视图中使用.removeFromSuperview()即可。只需确保没有任何内容依赖于这些视图(约束,值检查等)。
    1. 不是在Interface Builder中添加视图并使用@IBOutlet引用它们,只需通过代码添加仅将所需对象作为子视图。
    2. 副手,我不确定任何一种方法都必然会更好。" ...方法1.可能更容易获得您想要的对象(布局和其他属性),但方法2.可能更多一点"轻量级"并且将更容易修改。