ios 是否有方法从UIControl中删除所有UIAction?

pod7payv  于 2023-04-22  发布在  iOS
关注(0)|答案(3)|浏览(132)

或者是否有方法检查UIControl是否有任何UIAction?
有时我想改变一个UI控件的行为。

button.removeTarget(nil, action: nil), for: .touchUpInside)
button.addTarget(self, action: #selector(didTouchUpInside()), for: .for: .touchUpInside)
t1rydlwq

t1rydlwq1#

您可以使用enumerateEventHandlers来执行此操作:

button.enumerateEventHandlers { action, targetAction, event, stop in
    if let action = action {
        // This is a UIAction
        button.removeAction(action, for: event)
    }
    if let (target, selector) = targetAction {
        // This is target / action
        button.removeTarget(target, action: selector, for: event)
    }
    stop = true // Ends iterating early if you are done
}
qoefvg9y

qoefvg9y2#

根据jrturton所说的here,您可以将其转换为一个小扩展:

extension UIButton {
    func removeAllActions() {
        enumerateEventHandlers { action, _, event, _ in
            if let action = action {
                removeAction(action, for: event)
            }
        }
    }
}

现在,您可以在UIButton上调用removeAllActions()来获得相同的效果。

lvjbypge

lvjbypge3#

为什么不使用view.isUserInteractionEnabled = false?它将删除视图的所有交互功能

相关问题