簡體   English   中英

為什么新的 iOS 14 UIControl 動作語法如此糟糕?

[英]Why is the new iOS 14 UIControl action syntax so terrible?

iOS 14 中的新功能,我們可以將操作處理程序直接附加到 UIControl:

    let action = UIAction(title:"") { action in
        print("howdy!")
    }
    button.addAction(action, for: .touchUpInside)

這很酷,但語法令人憤怒。 我必須先形成 UIAction。 我必須給 UIAction 一個標題,即使該標題永遠不會出現在界面中。 沒有更好的方法嗎?

首先,您不需要提供標題。 這是(現在)合法的:

    let action = UIAction { action in
        print("howdy!")
    }
    button.addAction(action, for: .touchUpInside)

其次,你真的不需要單獨的行來定義動作,所以你可以這樣說:

    button.addAction(.init { action in
        print("howdy!")
    }, for: .touchUpInside)

然而,這仍然令人憤怒,因為現在我在addAction調用的中間有一個閉包。 它應該是一個尾隨閉包:顯而易見的解決方案是擴展:

extension UIControl {
    func addAction(for event: UIControl.Event, handler: @escaping UIActionHandler) {
        self.addAction(UIAction(handler:handler), for:event)
    }
}

問題解決了:現在我可以用我應該一直被允許的方式說話了:

    button.addAction(for: .touchUpInside) { action in
        print("howdy!")
    }

[額外信息:這個故事的sender在哪里? 在行動里面 UIAction 有一個sender屬性。 所以在該代碼中, action.sender是 UIButton。]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM