首页 > 解决方案 > 如何用经典的 UIButton 替换 UIBarButtonItem

问题描述

let rightBarBtn = UIBarButtonItem(title: "Light", style: .plain, target: self, action: #selector(rightBarBtnAction))
    self.navigationItem.rightBarButtonItem = rightBarBtn
}

@objc func rightBarBtnAction(sender: UIBarButtonItem) {
    if theme == .dark {
        sender.title = "Dark"
        theme = .light
        Style.themeLight()
    } else {
        sender.title = "Light"
        theme = .dark
        Style.themeDark()
    }
    self.view.backgroundColor = Style.bgColor
    calenderView.changeTheme()
}

这是一段代码,负责在我的日历中的两个主题之间切换,我想将 UIBarButton 切换到 UIButton 以更改其在屏幕上的位置。

到目前为止,这是我想出的:

    let themeSwitch = UIButton()
    themeSwitch.setTitle("Light", for: .normal)
    themeSwitch.backgroundColor = .darkGray
    themeSwitch.addTarget(self, action: #selector(themeSwitchAction), for: .touchUpInside)
}

override func viewWillLayoutSubviews() {
    super.viewWillLayoutSubviews()
    calenderView.myCollectionView.collectionViewLayout.invalidateLayout()
}

@objc func themeSwitchAction(sender: UIButton) {
    if theme == .dark {
        sender.currentTitle = "Dark"
        theme = .light
        Style.themeLight()
    } else {
        sender.currentTitle = "light"
        theme = .dark
        Style.themeDark()
    }
    self.view.backgroundColor = Style.bgColor
    calenderView.changeTheme()
}

正如您可能知道的那样,这不起作用。有人可以告诉我正确执行此操作的方法吗?

标签: iosswiftuibutton

解决方案


根据我从您的解释中了解到,如果您想从右到左或从左到右更改按钮的位置;无需使用**UIButton**.

您可以简单地将按钮分配给**self.navigationItem.leftBarButtonItem**

但无论如何,您可以添加一个**UIButton**内部**UIBarButtonItem**,如下所示:

在 UIBarButtonItem 中添加 UIButton



希望有帮助。


推荐阅读