gpt4 book ai didi

ios - 分段控件更改时更新 rightBarButtonItems

转载 作者:行者123 更新时间:2023-11-29 13:52:38 27 4
gpt4 key购买 nike

我想在 segmentedControl 更改时隐藏/显示 UIBarButtonItem,这是我的代码:

@objc fileprivate func handleSegmentedChange() {
switch segmentedControl.selectedSegmentIndex {
case index0:
// Set the proper rightBarButtonItems, in the first load this bar button items will be nil, this is why we have to check first
self.navigationItem.rightBarButtonItems?.append(UIBarButtonItem(image: #imageLiteral(resourceName: "Filter2"), style: .plain, target: self, action: #selector(openBottomSheet)))

default:
self.navigationItem.rightBarButtonItems?.remove(at: 0)
}
}

但是不更新 View (隐藏或显示任何内容)。

注意 我也试过在添加或删除项目之前将 rightBarButtonItems 设置为 nil,但是没有用。

我怎样才能达到预期的效果?

最佳答案

如果 rightBarButtonItems 在您尝试向其中添加项目或从中删除项目之前为 nil,则不会发生任何事情,因为您无法向不存在的数组添加项目或从中删除项目。

与其在 rightBarButtonItems 中添加/删除,不如尝试将其直接设置为您想要的项目,如下所示:

@objc fileprivate func handleSegmentedChange() {
switch segmentedControl.selectedSegmentIndex {
case 0:
let barButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "Filter2"),
style: .plain,
target: self,
action: #selector(openBottomSheet))
navigationItem.rightBarButtonItems = [barButtonItem]
// Note: If you're just dealing with one bar button item,
// you could also just use `navigationItem.rightBarButtonItem` like:
// navigationItem.rightBarButtonItem = barButtonItem

default:
navigationItem.rightBarButtonItems = nil // or `= []`
// Note: If you're just dealing with one bar button item,
// you could also just use `navigationItem.rightBarButtonItem` like:
// navigationItem.rightBarButtonItem = nil
}
}

关于ios - 分段控件更改时更新 rightBarButtonItems,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58904134/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com