【问题标题】:Why is the new iOS 14 UIControl action syntax so terrible?为什么新的 iOS 14 UIControl 操作语法如此糟糕?
【发布时间】:2020-11-27 01:01:19
【问题描述】:

iOS 14 中的新功能,我们可以将操作处理程序直接附加到 UIControl:

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

它的方式很酷,但语法令人愤怒。我必须先形成 UIAction。我必须给 UIAction 一个标题,即使该标题永远不会出现在界面中。没有更好的办法吗?

【问题讨论】:

    标签: ios uicontrol ios14 uiaction


    【解决方案1】:

    首先,您不需要提供标题。这是(现在)合法的:

        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。]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-05-08
      • 1970-01-01
      • 2020-05-10
      • 2010-11-19
      • 2010-09-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多