代码之家  ›  专栏  ›  技术社区  ›  Elye

willMove vs init,何时使用哪个?

  •  0
  • Elye  · 技术社区  · 6 年前

    UITextField ,即。 CurrencyTextField 根据 How to input currency format on a text field (from right to left) using Swift? willMove 功能如下

        override func willMove(toSuperview newSuperview: UIView?) {
            Formatter.currency.locale = locale
            addTarget(self, action: #selector(editingChanged), for: .editingChanged)
            keyboardType = .numberPad
            textAlignment = .right
            sendActions(for: .editingChanged)
        }
    

    不过,正如我之前了解到的,我们也可以在 init willMove公司

        override init(frame: CGRect) {
            super.init(frame: frame)
            Formatter.currency.locale = locale
            addTarget(self, action: #selector(editingChanged), for: .editingChanged)
            keyboardType = .numberPad
            textAlignment = .right
            sendActions(for: .editingChanged)
        }
    
        required init?(coder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    

    他们对我的案子似乎也有同样的反应。所以我不知道什么时候该用 初始化 willMove公司 ?

    deinit willMove公司 Why is deinit not called until UIView is added to parent again? 脱硝 willMove公司 初始化 willMove公司

    0 回复  |  直到 6 年前
        1
  •  3
  •   Sweeper    6 年前

    willMove 可以多次调用(每当视图的超级视图更改时)。 init 只被称为 曾经

    你要考虑的主要问题是:

    您希望代码只运行一次,还是每次视图的超级视图更改时都运行一次?

    例如,将打印以下代码 will move called 三次:

    class MyView: UIView {
        override func willMove(toSuperview newSuperview: UIView?) {
            print("will move called")
        }
    }
    
    let view1 = UIView()
    let view2 = UIView()
    let myView = MyView()
    view1.addSubview(myView) //*
    myView.removeFromSuperview() //*
    view2.addSubview(myView) //*
    

    每行都标有 * willMove公司 willMove公司 ,因为它“移动到一个新的超级视图” nil ".

    Formatter.currency.locale = locale
    addTarget(self, action: #selector(editingChanged), for: .editingChanged)
    keyboardType = .numberPad
    textAlignment = .right
    sendActions(for: .editingChanged)
    

    我认为不止一次地执行上面的代码并没有多大区别,所以将它放在两种方法中都可以。


    初始化 在创建视图后立即调用,而 在将视图添加到superview之前不会发生。这在一些罕见的情况下可能会有所不同。