有时失效是个问题。似乎您需要再次将按钮设置到导航栏。它是如此聪明,你首先需要设置它
nil
甚至会产生效果。
这就是我试过的:
let buttonImage: UIImage = #imageLiteral(resourceName: "icons8-slider-30")
let filterMenuNavButton = UIBarButtonItem(image: buttonImage, style: .plain, target: nil, action: nil)
self.navigationItem.rightBarButtonItem = filterMenuNavButton
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
let filterActivityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray)
filterMenuNavButton.customView = filterActivityIndicator
filterActivityIndicator.startAnimating()
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
filterActivityIndicator.stopAnimating()
filterMenuNavButton.customView = nil
filterMenuNavButton.setBackgroundImage(buttonImage, for: .normal, barMetrics: .default)
self.navigationItem.rightBarButtonItem = nil
self.navigationItem.rightBarButtonItem = filterMenuNavButton
}
}
我不确定你的设置是什么,但是我用了一个简单的导航视图控制器并把这个代码放进去。
viewDidLoad
它的当前(根)视图控制器。
最后一部分可能是你想要的,你需要:
-
设置自定义视图以清除
-
添加图像或更改其他按钮属性
-
清除按钮项(设置为零)
-
将按钮项设置回所需项
我希望这能解决你的问题。不过,我必须说,在指示器运行时创建一个新的按钮项可能更有意义。检查以下各项:
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
let preservedButtonItem = self.navigationItem.rightBarButtonItem
let filterActivityIndicator: UIActivityIndicatorView = {
let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: activityIndicator)
return activityIndicator
}()
filterActivityIndicator.startAnimating()
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
filterActivityIndicator.stopAnimating()
self.navigationItem.rightBarButtonItem = preservedButtonItem
}
}
编辑:多个按钮
对于多个按钮,情况应该非常相似。请尝试玩以下游戏:
guard let oldItems = navigationItem.rightBarButtonItems else {
return
}
var newItems = oldItems
// Find the index of item so we may ereplace it
guard let index = newItems.index(where: { $0 === filterMenuNavButton }) else {
return
}
let activityIndicator: UIActivityIndicatorView = {
let activity = UIActivityIndicatorView()
return activity
}()
newItems[index] = UIBarButtonItem(customView: activityIndicator)
navigationItem.rightBarButtonItems = newItems
DispatchQueue.main.asyncAfter(deadline: .now()+2.0) {
self.navigationItem.rightBarButtonItems = oldItems
}