3

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

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

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

4

1 回答 1

6

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

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

于 2020-08-06T17:47:15.937 回答