【问题标题】:Extension of UIBarButtonItem when touchesBegantouchesBegan 时 UIBarButtonItem 的扩展
【发布时间】:2018-10-18 10:36:36
【问题描述】:

我实际上正在管理与 ReachabilityManager 类的连接。

我创建了一个 toast,它显示连接丢失和恢复的时间。 我还创建了两个扩展(UIButton 和 UISwitch),并在其上覆盖了 func touchesBegan 以检查和播放按钮/开关的操作或仅显示带有错误消息的 toast(并且不播放按钮/开关的选择器)。

这里要理解我的 UIButton 扩展:

extension UIButton {
    open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if ReachabilityManager.shared.reachability.connection == .none {
            ReachabilityManager.shared.customConnectionToast(ToastStyle.connectionLost.applyStyle(),
                                  description: NSLocalizedString("no_connection_error_message", comment: ""))
        } else {
            sendActions(for: UIControlEvents.allTouchEvents)
        }
    }
}

我现在需要为 UIBarButtonItem 创建相同的扩展,但问题是该对象没有 touchesBegan 操作,我不知道如何制作类似于 UIbutton 和 UISwitch 扩展的东西。关于我为什么要这样做的另一个信息是我无法重构应用程序的所有 barbutton 项目(这需要我 2 周的时间)。为此,我必须找到一种扩展方式或其他方式,但绝对是通用的解决方案。

如果有人有任何想法,我将不胜感激。

提前谢谢你。

亲切的问候,

【问题讨论】:

    标签: ios swift uibarbuttonitem


    【解决方案1】:

    一个快速的解决方案:使用UIButton 并将其设为UIBarButtonItem,然后您可以使用您发布的类别(UIButton 的扩展)到您的新按钮作为barButtonItem。

    像这样:

    internal lazy var button_Close: UIButton = {
            let button = UIButton(type: .custom)
            button.setImage(.close, for: .normal)
            button.imageEdgeInsets = UIEdgeInsets.init(top: 0, left: -30, bottom: 0, right: 0)
            button.addTarget(self, action: #selector(back(_:)), for: .touchUpInside)
            return button
        }()
    

    将其设为 barButton 项:

    override func viewDidLoad() {
        super.viewDidLoad()
    
        let barButton = UIBarButtonItem(customView: self.button_Close)
        self.button_Close.frame = CGRect(x: 0, y: 0, width: 55.0, height: 44.0)
        let negativeSpacer = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.fixedSpace, target: nil, action: nil)
        if #available(iOS 11.0, *) {
            negativeSpacer.width = -30
        }
        self.navigationItem.leftBarButtonItems = [negativeSpacer, barButton]
    }
    

    我希望这会有所帮助!

    【讨论】:

    • 感谢@Glenn 的快速回答,但问题是应用程序很大,我无法重构应用程序的所有 barbutton 项目(这需要 2 周)我必须找到一种方法带有扩展名或其他内容,但绝对是通用解决方案。
    • Welp,恐怕你别无选择,只能使用这种方法。我希望有另一种方式,我也想知道。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-04
    • 1970-01-01
    相关资源
    最近更新 更多