如何使用具有自动布局的 init(frame:) 实例化自定义 UIView 子类?

How to instantiate a custom UIView subclass with init(frame:) with auto layout?

我正在制作一个 ios 应用程序,并依靠 AutoLayout 约束来设置视图和子视图布局的大小。

我制作了 UIScrollView 的自定义子 class,见下文。当我写它的 init 方法时,我看到它的超级 class 只有 init(frame:) 可以覆盖。但是因为我使用的是自动布局,所以我不应该设置框架。

那么我应该如何编写 init 方法呢?我可以传入一个虚拟 frame 值吗:

MyCollectionView: UIScrollView {

   init() {
        super.init(CGRect(x:0, y:0, width:0, height:0))
    }

}

用法:

ViewController:UIViewController {

let myScrollView = MyScrollView()

}

您不必像使用自动布局时那样担心 setting/not 个框架

let myScrollView = MyScrollView()
myScrollView.translatesAutoresizingMaskIntoConstraints = false

框架将对 translatesAutoresizingMaskIntoConstraints 设置为 false 没有影响,所以

class MyScrollView: UIScrollView {

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

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

    func setUp() {

    }

}

let gg = MyScrollView(frame: .zero)
gg.translatesAutoresizingMaskIntoConstraints = false
// add constraints